[obj2yaml] - Stop triggering UB when dumping corrupted strings.
[llvm-complete.git] / unittests / MC / MCInstPrinter.cpp
blob069437d97a732865a18312610c1d16c5d1d2ed72
1 //===- llvm/unittest/MC/MCInstPrinter.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 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCInstPrinter.h"
10 #include "llvm/MC/MCAsmInfo.h"
11 #include "llvm/MC/MCInstrInfo.h"
12 #include "llvm/Support/TargetRegistry.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Target/TargetOptions.h"
16 #include "gtest/gtest.h"
18 using namespace llvm;
20 namespace {
21 class MCInstPrinterTest : public ::testing::Test {
22 public:
23 std::unique_ptr<MCRegisterInfo> MRI;
24 std::unique_ptr<MCAsmInfo> MAI;
25 std::unique_ptr<const MCInstrInfo> MII;
26 std::unique_ptr<MCInstPrinter> Printer;
28 MCInstPrinterTest() {
29 llvm::InitializeAllTargetInfos();
30 llvm::InitializeAllTargetMCs();
32 std::string TripleName = "x86_64-pc-linux";
33 std::string ErrorStr;
35 const Target *TheTarget =
36 TargetRegistry::lookupTarget(TripleName, ErrorStr);
38 // If we didn't build x86, do not run the test.
39 if (!TheTarget)
40 return;
42 MRI.reset(TheTarget->createMCRegInfo(TripleName));
43 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
44 MII.reset(TheTarget->createMCInstrInfo());
45 Printer.reset(TheTarget->createMCInstPrinter(
46 Triple(TripleName), MAI->getAssemblerDialect(), *MAI, *MII, *MRI));
49 template <typename T> std::string formatHex(T i) {
50 std::string Buffer;
51 raw_string_ostream OS(Buffer);
52 OS << Printer->formatHex(i);
53 OS.flush();
54 return Buffer;
57 } // namespace
59 TEST_F(MCInstPrinterTest, formatHex) {
60 if (!Printer)
61 return;
63 EXPECT_EQ("0x1", formatHex<int64_t>(1));
64 EXPECT_EQ("0x7fffffffffffffff",
65 formatHex(std::numeric_limits<int64_t>::max()));
66 EXPECT_EQ("-0x8000000000000000",
67 formatHex(std::numeric_limits<int64_t>::min()));