1//===- TargetUtils.cpp - utils for obtaining generic target backend 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#include "mlir/Target/LLVMIR/Transforms/Passes.h"
10
11#include "mlir/Dialect/DLTI/DLTI.h"
12#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
13#include "mlir/Target/LLVMIR/Import.h"
14
15#include "llvm/MC/TargetRegistry.h"
16#include "llvm/Support/DebugLog.h"
17#include "llvm/Support/TargetSelect.h"
18#include "llvm/Target/TargetMachine.h"
19
20#define DEBUG_TYPE "mlir-llvm-target-utils"
21
22namespace mlir {
23namespace LLVM {
24namespace detail {
25void initializeBackendsOnce() {
26 static const auto initOnce = [] {
27 // Ensure that the targets, that LLVM has been configured to support,
28 // are loaded into the TargetRegistry.
29 llvm::InitializeAllTargets();
30 llvm::InitializeAllTargetMCs();
31 return true;
32 }();
33 (void)initOnce; // Dummy usage.
34}
35
36FailureOr<std::unique_ptr<llvm::TargetMachine>>
37getTargetMachine(mlir::LLVM::TargetAttrInterface attr) {
38 StringRef triple = attr.getTriple();
39 StringRef chipAKAcpu = attr.getChip();
40 // NB: `TargetAttrInterface::getFeatures()` is coarsely typed to work around
41 // cyclic dependency issue in tablegen files.
42 auto featuresAttr =
43 llvm::cast_if_present<LLVM::TargetFeaturesAttr>(Val: attr.getFeatures());
44 std::string features = featuresAttr ? featuresAttr.getFeaturesString() : "";
45
46 llvm::Triple parsedTriple(triple);
47 std::string error;
48 const llvm::Target *target =
49 llvm::TargetRegistry::lookupTarget(TheTriple: parsedTriple, Error&: error);
50 if (!target || !error.empty()) {
51 LDBG() << "Looking up target '" << triple << "' failed: " << error << "\n";
52 return failure();
53 }
54
55 return std::unique_ptr<llvm::TargetMachine>(
56 target->createTargetMachine(TT: parsedTriple, CPU: chipAKAcpu, Features: features, Options: {}, RM: {}));
57}
58
59FailureOr<llvm::DataLayout>
60getDataLayout(mlir::LLVM::TargetAttrInterface attr) {
61 FailureOr<std::unique_ptr<llvm::TargetMachine>> targetMachine =
62 getTargetMachine(attr);
63 if (failed(Result: targetMachine)) {
64 LDBG() << "Failed to retrieve the target machine for data layout.\n";
65 return failure();
66 }
67 return llvm::DataLayout(
68 (targetMachine.value())->getTargetTriple().computeDataLayout());
69}
70
71} // namespace detail
72} // namespace LLVM
73} // namespace mlir
74