MLIR 22.0.0git
TargetUtils.cpp
Go to the documentation of this file.
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
10
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 {
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>(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(parsedTriple, 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(parsedTriple, chipAKAcpu, features, {}, {}));
57}
58
59FailureOr<llvm::DataLayout>
60getDataLayout(mlir::LLVM::TargetAttrInterface attr) {
61 FailureOr<std::unique_ptr<llvm::TargetMachine>> targetMachine =
62 getTargetMachine(attr);
63 if (failed(targetMachine)) {
64 LDBG() << "Failed to retrieve the target machine for data layout.\n";
65 return failure();
66 }
67 return (targetMachine.value())->createDataLayout();
68}
69
70} // namespace detail
71} // namespace LLVM
72} // namespace mlir
FailureOr< std::unique_ptr< llvm::TargetMachine > > getTargetMachine(mlir::LLVM::TargetAttrInterface attr)
Helper to obtain the TargetMachine specified by the properties of the TargetAttrInterface-implementin...
FailureOr< llvm::DataLayout > getDataLayout(mlir::LLVM::TargetAttrInterface attr)
Helper to obtain the DataLayout of the target specified by the properties of the TargetAttrInterface-...
void initializeBackendsOnce()
Idempotent helper to register/initialize all backends that LLVM has been configured to support.
Include the generated interface declarations.