authorbors <bors@rust-lang.org> 2024-06-27 01:18:56 UTC
committerbors <bors@rust-lang.org> 2024-06-27 01:18:56 UTC
log7033f9b14a37f4a00766d6c01326600b31f3a716
treeb537982ef384295bb71a18ce760896fb65b35191
parent4bc39f028d14c24b04dd17dc425432c6ec354536
parentc163d5c99d381efb74c02182996b69b32ecfcff1

Auto merge of #123918 - DianQK:clang-format, r=Kobzol

Use `clang-format` in `tidy` to check the C++ code style under `llvm-wrapper` Fixes #123510. Based on the discussion at https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/Enable.20.60clang-format.60.20for.20.60rustc.60.20compiler-team.23756/near/443562800, we can use clang-format from pip to achieve the code formatting. r? `@Kobzol`

14 files changed, 909 insertions(+), 834 deletions(-)

.clang-format created+1
......@@ -0,0 +1 @@
1BasedOnStyle: LLVM
.reuse/dep5+1
......@@ -29,6 +29,7 @@ Files: compiler/*
2929 x
3030 x.ps1
3131 x.py
32 .clang-format
3233 .editorconfig
3334 .git-blame-ignore-revs
3435 .gitattributes
Cargo.lock+1
......@@ -5627,6 +5627,7 @@ dependencies = [
56275627 "regex",
56285628 "rustc-hash",
56295629 "semver",
5630 "similar",
56305631 "termcolor",
56315632 "walkdir",
56325633]
compiler/rustc_llvm/llvm-wrapper/ArchiveWrapper.cpp+14-19
......@@ -13,10 +13,7 @@ struct RustArchiveMember {
1313 Archive::Child Child;
1414
1515 RustArchiveMember()
16 : Filename(nullptr), Name(nullptr),
17 Child(nullptr, nullptr, nullptr)
18 {
19 }
16 : Filename(nullptr), Name(nullptr), Child(nullptr, nullptr, nullptr) {}
2017 ~RustArchiveMember() {}
2118};
2219
......@@ -27,11 +24,8 @@ struct RustArchiveIterator {
2724 std::unique_ptr<Error> Err;
2825
2926 RustArchiveIterator(Archive::child_iterator Cur, Archive::child_iterator End,
30 std::unique_ptr<Error> Err)
31 : First(true),
32 Cur(Cur),
33 End(End),
34 Err(std::move(Err)) {}
27 std::unique_ptr<Error> Err)
28 : First(true), Cur(Cur), End(End), Err(std::move(Err)) {}
3529};
3630
3731enum class LLVMRustArchiveKind {
......@@ -66,8 +60,8 @@ typedef Archive::Child const *LLVMRustArchiveChildConstRef;
6660typedef RustArchiveIterator *LLVMRustArchiveIteratorRef;
6761
6862extern "C" LLVMRustArchiveRef LLVMRustOpenArchive(char *Path) {
69 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
70 MemoryBuffer::getFile(Path, /*IsText*/false, /*RequiresNullTerminator=*/false);
63 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr = MemoryBuffer::getFile(
64 Path, /*IsText*/ false, /*RequiresNullTerminator=*/false);
7165 if (!BufOr) {
7266 LLVMRustSetLastError(BufOr.getError().message().c_str());
7367 return nullptr;
......@@ -146,8 +140,8 @@ extern "C" const char *
146140LLVMRustArchiveChildName(LLVMRustArchiveChildConstRef Child, size_t *Size) {
147141 Expected<StringRef> NameOrErr = Child->getName();
148142 if (!NameOrErr) {
149 // rustc_codegen_llvm currently doesn't use this error string, but it might be
150 // useful in the future, and in the meantime this tells LLVM that the
143 // rustc_codegen_llvm currently doesn't use this error string, but it might
144 // be useful in the future, and in the meantime this tells LLVM that the
151145 // error was not ignored and that it shouldn't abort the process.
152146 LLVMRustSetLastError(toString(NameOrErr.takeError()).c_str());
153147 return nullptr;
......@@ -172,10 +166,9 @@ extern "C" void LLVMRustArchiveMemberFree(LLVMRustArchiveMemberRef Member) {
172166 delete Member;
173167}
174168
175extern "C" LLVMRustResult
176LLVMRustWriteArchive(char *Dst, size_t NumMembers,
177 const LLVMRustArchiveMemberRef *NewMembers,
178 bool WriteSymbtab, LLVMRustArchiveKind RustKind, bool isEC) {
169extern "C" LLVMRustResult LLVMRustWriteArchive(
170 char *Dst, size_t NumMembers, const LLVMRustArchiveMemberRef *NewMembers,
171 bool WriteSymbtab, LLVMRustArchiveKind RustKind, bool isEC) {
179172
180173 std::vector<NewArchiveMember> Members;
181174 auto Kind = fromRust(RustKind);
......@@ -206,8 +199,10 @@ LLVMRustWriteArchive(char *Dst, size_t NumMembers,
206199#if LLVM_VERSION_LT(18, 0)
207200 auto Result = writeArchive(Dst, Members, WriteSymbtab, Kind, true, false);
208201#else
209 auto SymtabMode = WriteSymbtab ? SymtabWritingMode::NormalSymtab : SymtabWritingMode::NoSymtab;
210 auto Result = writeArchive(Dst, Members, SymtabMode, Kind, true, false, nullptr, isEC);
202 auto SymtabMode = WriteSymbtab ? SymtabWritingMode::NormalSymtab
203 : SymtabWritingMode::NoSymtab;
204 auto Result =
205 writeArchive(Dst, Members, SymtabMode, Kind, true, false, nullptr, isEC);
211206#endif
212207 if (!Result)
213208 return LLVMRustResult::Success;
compiler/rustc_llvm/llvm-wrapper/Linker.cpp+5-13
......@@ -1,5 +1,5 @@
1#include "SuppressLLVMWarnings.h"
21#include "llvm/Linker/Linker.h"
2#include "SuppressLLVMWarnings.h"
33
44#include "LLVMWrapper.h"
55
......@@ -9,26 +9,18 @@ struct RustLinker {
99 Linker L;
1010 LLVMContext &Ctx;
1111
12 RustLinker(Module &M) :
13 L(M),
14 Ctx(M.getContext())
15 {}
12 RustLinker(Module &M) : L(M), Ctx(M.getContext()) {}
1613};
1714
18extern "C" RustLinker*
19LLVMRustLinkerNew(LLVMModuleRef DstRef) {
15extern "C" RustLinker *LLVMRustLinkerNew(LLVMModuleRef DstRef) {
2016 Module *Dst = unwrap(DstRef);
2117
2218 return new RustLinker(*Dst);
2319}
2420
25extern "C" void
26LLVMRustLinkerFree(RustLinker *L) {
27 delete L;
28}
21extern "C" void LLVMRustLinkerFree(RustLinker *L) { delete L; }
2922
30extern "C" bool
31LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) {
23extern "C" bool LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) {
3224 std::unique_ptr<MemoryBuffer> Buf =
3325 MemoryBuffer::getMemBufferCopy(StringRef(BC, Len));
3426
compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp+227-243
......@@ -2,23 +2,25 @@
22
33#include <cstddef>
44#include <iomanip>
5#include <vector>
65#include <set>
6#include <vector>
77
88#include "LLVMWrapper.h"
99
1010#include "llvm/Analysis/AliasAnalysis.h"
1111#include "llvm/Analysis/TargetLibraryInfo.h"
1212#include "llvm/Analysis/TargetTransformInfo.h"
13#include "llvm/Bitcode/BitcodeWriter.h"
1314#include "llvm/CodeGen/CommandFlags.h"
1415#include "llvm/CodeGen/TargetSubtargetInfo.h"
15#include "llvm/IR/AutoUpgrade.h"
1616#include "llvm/IR/AssemblyAnnotationWriter.h"
17#include "llvm/IR/AutoUpgrade.h"
1718#include "llvm/IR/IntrinsicInst.h"
1819#include "llvm/IR/Verifier.h"
20#include "llvm/LTO/LTO.h"
1921#include "llvm/MC/TargetRegistry.h"
20#include "llvm/Object/ObjectFile.h"
2122#include "llvm/Object/IRObjectFile.h"
23#include "llvm/Object/ObjectFile.h"
2224#include "llvm/Passes/PassBuilder.h"
2325#include "llvm/Passes/PassPlugin.h"
2426#include "llvm/Passes/StandardInstrumentations.h"
......@@ -33,26 +35,24 @@
3335#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
3436#include "llvm/Transforms/Utils/AddDiscriminators.h"
3537#include "llvm/Transforms/Utils/FunctionImportUtils.h"
36#include "llvm/LTO/LTO.h"
37#include "llvm/Bitcode/BitcodeWriter.h"
3838#if LLVM_VERSION_GE(18, 0)
3939#include "llvm/TargetParser/Host.h"
4040#endif
41#include "llvm/Support/TimeProfiler.h"
4142#include "llvm/Transforms/Instrumentation.h"
4243#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
4344#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
44#include "llvm/Support/TimeProfiler.h"
4545#if LLVM_VERSION_GE(19, 0)
4646#include "llvm/Support/PGOOptions.h"
4747#endif
4848#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
49#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
4950#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
50#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
5151#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
52#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
52#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
53#include "llvm/Transforms/Utils.h"
5354#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
5455#include "llvm/Transforms/Utils/NameAnonGlobals.h"
55#include "llvm/Transforms/Utils.h"
5656
5757using namespace llvm;
5858
......@@ -74,7 +74,7 @@ extern "C" void LLVMRustTimeTraceProfilerFinishThread() {
7474 timeTraceProfilerFinishThread();
7575}
7676
77extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) {
77extern "C" void LLVMRustTimeTraceProfilerFinish(const char *FileName) {
7878 auto FN = StringRef(FileName);
7979 std::error_code EC;
8080 auto OS = raw_fd_ostream(FN, EC, sys::fs::CD_CreateAlways);
......@@ -188,7 +188,7 @@ extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) {
188188 SUBTARGET_HEXAGON \
189189 SUBTARGET_XTENSA \
190190 SUBTARGET_RISCV \
191 SUBTARGET_LOONGARCH \
191 SUBTARGET_LOONGARCH
192192
193193#define SUBTARGET(x) \
194194 namespace llvm { \
......@@ -215,8 +215,7 @@ enum class LLVMRustCodeModel {
215215 None,
216216};
217217
218static std::optional<CodeModel::Model>
219fromRust(LLVMRustCodeModel Model) {
218static std::optional<CodeModel::Model> fromRust(LLVMRustCodeModel Model) {
220219 switch (Model) {
221220 case LLVMRustCodeModel::Tiny:
222221 return CodeModel::Tiny;
......@@ -243,9 +242,9 @@ enum class LLVMRustCodeGenOptLevel {
243242};
244243
245244#if LLVM_VERSION_GE(18, 0)
246 using CodeGenOptLevelEnum = llvm::CodeGenOptLevel;
245using CodeGenOptLevelEnum = llvm::CodeGenOptLevel;
247246#else
248 using CodeGenOptLevelEnum = llvm::CodeGenOpt::Level;
247using CodeGenOptLevelEnum = llvm::CodeGenOpt::Level;
249248#endif
250249
251250static CodeGenOptLevelEnum fromRust(LLVMRustCodeGenOptLevel Level) {
......@@ -319,48 +318,49 @@ static Reloc::Model fromRust(LLVMRustRelocModel RustReloc) {
319318}
320319
321320/// getLongestEntryLength - Return the length of the longest entry in the table.
322template<typename KV>
323static size_t getLongestEntryLength(ArrayRef<KV> Table) {
321template <typename KV> static size_t getLongestEntryLength(ArrayRef<KV> Table) {
324322 size_t MaxLen = 0;
325323 for (auto &I : Table)
326324 MaxLen = std::max(MaxLen, std::strlen(I.Key));
327325 return MaxLen;
328326}
329327
330using PrintBackendInfo = void(void*, const char* Data, size_t Len);
328using PrintBackendInfo = void(void *, const char *Data, size_t Len);
331329
332330extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM,
333 const char* TargetCPU,
334 PrintBackendInfo Print,
335 void* Out) {
331 const char *TargetCPU,
332 PrintBackendInfo Print, void *Out) {
336333 const TargetMachine *Target = unwrap(TM);
337 const Triple::ArchType HostArch = Triple(sys::getDefaultTargetTriple()).getArch();
334 const Triple::ArchType HostArch =
335 Triple(sys::getDefaultTargetTriple()).getArch();
338336 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
339337
340338 std::ostringstream Buf;
341339
342340 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
343 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getAllProcessorDescriptions();
341 const ArrayRef<SubtargetSubTypeKV> CPUTable =
342 MCInfo->getAllProcessorDescriptions();
344343 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
345344
346345 Buf << "Available CPUs for this target:\n";
347346 // Don't print the "native" entry when the user specifies --target with a
348347 // different arch since that could be wrong or misleading.
349348 if (HostArch == TargetArch) {
350 MaxCPULen = std::max(MaxCPULen, (unsigned) std::strlen("native"));
349 MaxCPULen = std::max(MaxCPULen, (unsigned)std::strlen("native"));
351350 const StringRef HostCPU = sys::getHostCPUName();
352351 Buf << " " << std::left << std::setw(MaxCPULen) << "native"
353352 << " - Select the CPU of the current host "
354 "(currently " << HostCPU.str() << ").\n";
353 "(currently "
354 << HostCPU.str() << ").\n";
355355 }
356356 for (auto &CPU : CPUTable) {
357357 // Compare cpu against current target to label the default
358358 if (strcmp(CPU.Key, TargetCPU) == 0) {
359359 Buf << " " << std::left << std::setw(MaxCPULen) << CPU.Key
360360 << " - This is the default target CPU for the current build target "
361 "(currently " << Target->getTargetTriple().str() << ").";
362 }
363 else {
361 "(currently "
362 << Target->getTargetTriple().str() << ").";
363 } else {
364364 Buf << " " << CPU.Key;
365365 }
366366 Buf << "\n";
......@@ -374,7 +374,8 @@ extern "C" size_t LLVMRustGetTargetFeaturesCount(LLVMTargetMachineRef TM) {
374374#if LLVM_VERSION_GE(18, 0)
375375 const TargetMachine *Target = unwrap(TM);
376376 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
377 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getAllProcessorFeatures();
377 const ArrayRef<SubtargetFeatureKV> FeatTable =
378 MCInfo->getAllProcessorFeatures();
378379 return FeatTable.size();
379380#else
380381 return 0;
......@@ -382,18 +383,20 @@ extern "C" size_t LLVMRustGetTargetFeaturesCount(LLVMTargetMachineRef TM) {
382383}
383384
384385extern "C" void LLVMRustGetTargetFeature(LLVMTargetMachineRef TM, size_t Index,
385 const char** Feature, const char** Desc) {
386 const char **Feature,
387 const char **Desc) {
386388#if LLVM_VERSION_GE(18, 0)
387389 const TargetMachine *Target = unwrap(TM);
388390 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
389 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getAllProcessorFeatures();
391 const ArrayRef<SubtargetFeatureKV> FeatTable =
392 MCInfo->getAllProcessorFeatures();
390393 const SubtargetFeatureKV Feat = FeatTable[Index];
391394 *Feature = Feat.Key;
392395 *Desc = Feat.Desc;
393396#endif
394397}
395398
396extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
399extern "C" const char *LLVMRustGetHostCPUName(size_t *len) {
397400 StringRef Name = sys::getHostCPUName();
398401 *len = Name.size();
399402 return Name.data();
......@@ -403,19 +406,11 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
403406 const char *TripleStr, const char *CPU, const char *Feature,
404407 const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocModel RustReloc,
405408 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
406 bool FunctionSections,
407 bool DataSections,
408 bool UniqueSectionNames,
409 bool TrapUnreachable,
410 bool Singlethread,
411 bool AsmComments,
412 bool EmitStackSizeSection,
413 bool RelaxELFRelocations,
414 bool UseInitArray,
415 const char *SplitDwarfFile,
416 const char *OutputObjFile,
417 const char *DebugInfoCompression,
418 bool UseEmulatedTls,
409 bool FunctionSections, bool DataSections, bool UniqueSectionNames,
410 bool TrapUnreachable, bool Singlethread, bool AsmComments,
411 bool EmitStackSizeSection, bool RelaxELFRelocations, bool UseInitArray,
412 const char *SplitDwarfFile, const char *OutputObjFile,
413 const char *DebugInfoCompression, bool UseEmulatedTls,
419414 const char *ArgsCstrBuff, size_t ArgsCstrBuffLen) {
420415
421416 auto OptLevel = fromRust(RustOptLevel);
......@@ -444,18 +439,20 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
444439 Options.MCOptions.PreserveAsmComments = AsmComments;
445440 Options.MCOptions.ABIName = ABIStr;
446441 if (SplitDwarfFile) {
447 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
442 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
448443 }
449444 if (OutputObjFile) {
450 Options.ObjectFilenameForDebug = OutputObjFile;
445 Options.ObjectFilenameForDebug = OutputObjFile;
451446 }
452 if (!strcmp("zlib", DebugInfoCompression) && llvm::compression::zlib::isAvailable()) {
447 if (!strcmp("zlib", DebugInfoCompression) &&
448 llvm::compression::zlib::isAvailable()) {
453449#if LLVM_VERSION_GE(19, 0)
454450 Options.MCOptions.CompressDebugSections = DebugCompressionType::Zlib;
455451#else
456452 Options.CompressDebugSections = DebugCompressionType::Zlib;
457453#endif
458 } else if (!strcmp("zstd", DebugInfoCompression) && llvm::compression::zstd::isAvailable()) {
454 } else if (!strcmp("zstd", DebugInfoCompression) &&
455 llvm::compression::zstd::isAvailable()) {
459456#if LLVM_VERSION_GE(19, 0)
460457 Options.MCOptions.CompressDebugSections = DebugCompressionType::Zstd;
461458#else
......@@ -499,24 +496,21 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
499496
500497 Options.EmitStackSizeSection = EmitStackSizeSection;
501498
502
503 if (ArgsCstrBuff != nullptr)
504 {
499 if (ArgsCstrBuff != nullptr) {
505500 int buffer_offset = 0;
506501 assert(ArgsCstrBuff[ArgsCstrBuffLen - 1] == '\0');
507502
508503 const size_t arg0_len = std::strlen(ArgsCstrBuff);
509 char* arg0 = new char[arg0_len + 1];
504 char *arg0 = new char[arg0_len + 1];
510505 memcpy(arg0, ArgsCstrBuff, arg0_len);
511506 arg0[arg0_len] = '\0';
512507 buffer_offset += arg0_len + 1;
513508
514 const int num_cmd_arg_strings =
515 std::count(&ArgsCstrBuff[buffer_offset], &ArgsCstrBuff[ArgsCstrBuffLen], '\0');
509 const int num_cmd_arg_strings = std::count(
510 &ArgsCstrBuff[buffer_offset], &ArgsCstrBuff[ArgsCstrBuffLen], '\0');
516511
517 std::string* cmd_arg_strings = new std::string[num_cmd_arg_strings];
518 for (int i = 0; i < num_cmd_arg_strings; ++i)
519 {
512 std::string *cmd_arg_strings = new std::string[num_cmd_arg_strings];
513 for (int i = 0; i < num_cmd_arg_strings; ++i) {
520514 assert(buffer_offset < ArgsCstrBuffLen);
521515 const int len = std::strlen(ArgsCstrBuff + buffer_offset);
522516 cmd_arg_strings[i] = std::string(&ArgsCstrBuff[buffer_offset], len);
......@@ -527,7 +521,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
527521
528522 Options.MCOptions.Argv0 = arg0;
529523 Options.MCOptions.CommandLineArgs =
530 llvm::ArrayRef<std::string>(cmd_arg_strings, num_cmd_arg_strings);
524 llvm::ArrayRef<std::string>(cmd_arg_strings, num_cmd_arg_strings);
531525 }
532526
533527 TargetMachine *TM = TheTarget->createTargetMachine(
......@@ -537,7 +531,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
537531
538532extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
539533
540 MCTargetOptions& MCOptions = unwrap(TM)->Options.MCOptions;
534 MCTargetOptions &MCOptions = unwrap(TM)->Options.MCOptions;
541535 delete[] MCOptions.Argv0;
542536 delete[] MCOptions.CommandLineArgs.data();
543537
......@@ -613,7 +607,7 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
613607 auto DOS = raw_fd_ostream(DwoPath, EC, sys::fs::OF_None);
614608 EC.clear();
615609 if (EC)
616 ErrorInfo = EC.message();
610 ErrorInfo = EC.message();
617611 if (ErrorInfo != "") {
618612 LLVMRustSetLastError(ErrorInfo.c_str());
619613 return LLVMRustResult::Failure;
......@@ -633,10 +627,12 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
633627 return LLVMRustResult::Success;
634628}
635629
636extern "C" typedef void (*LLVMRustSelfProfileBeforePassCallback)(void*, // LlvmSelfProfiler
637 const char*, // pass name
638 const char*); // IR name
639extern "C" typedef void (*LLVMRustSelfProfileAfterPassCallback)(void*); // LlvmSelfProfiler
630extern "C" typedef void (*LLVMRustSelfProfileBeforePassCallback)(
631 void *, // LlvmSelfProfiler
632 const char *, // pass name
633 const char *); // IR name
634extern "C" typedef void (*LLVMRustSelfProfileAfterPassCallback)(
635 void *); // LlvmSelfProfiler
640636
641637std::string LLVMRustwrappedIrGetName(const llvm::Any &WrappedIr) {
642638 if (const auto *Cast = any_cast<const Module *>(&WrappedIr))
......@@ -650,35 +646,35 @@ std::string LLVMRustwrappedIrGetName(const llvm::Any &WrappedIr) {
650646 return "<UNKNOWN>";
651647}
652648
653
654649void LLVMSelfProfileInitializeCallbacks(
655 PassInstrumentationCallbacks& PIC, void* LlvmSelfProfiler,
650 PassInstrumentationCallbacks &PIC, void *LlvmSelfProfiler,
656651 LLVMRustSelfProfileBeforePassCallback BeforePassCallback,
657652 LLVMRustSelfProfileAfterPassCallback AfterPassCallback) {
658 PIC.registerBeforeNonSkippedPassCallback([LlvmSelfProfiler, BeforePassCallback](
659 StringRef Pass, llvm::Any Ir) {
660 std::string PassName = Pass.str();
661 std::string IrName = LLVMRustwrappedIrGetName(Ir);
662 BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str());
663 });
653 PIC.registerBeforeNonSkippedPassCallback(
654 [LlvmSelfProfiler, BeforePassCallback](StringRef Pass, llvm::Any Ir) {
655 std::string PassName = Pass.str();
656 std::string IrName = LLVMRustwrappedIrGetName(Ir);
657 BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str());
658 });
664659
665660 PIC.registerAfterPassCallback(
666 [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, llvm::Any IR,
667 const PreservedAnalyses &Preserved) {
661 [LlvmSelfProfiler, AfterPassCallback](
662 StringRef Pass, llvm::Any IR, const PreservedAnalyses &Preserved) {
668663 AfterPassCallback(LlvmSelfProfiler);
669664 });
670665
671666 PIC.registerAfterPassInvalidatedCallback(
672 [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, const PreservedAnalyses &Preserved) {
667 [LlvmSelfProfiler,
668 AfterPassCallback](StringRef Pass, const PreservedAnalyses &Preserved) {
673669 AfterPassCallback(LlvmSelfProfiler);
674670 });
675671
676 PIC.registerBeforeAnalysisCallback([LlvmSelfProfiler, BeforePassCallback](
677 StringRef Pass, llvm::Any Ir) {
678 std::string PassName = Pass.str();
679 std::string IrName = LLVMRustwrappedIrGetName(Ir);
680 BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str());
681 });
672 PIC.registerBeforeAnalysisCallback(
673 [LlvmSelfProfiler, BeforePassCallback](StringRef Pass, llvm::Any Ir) {
674 std::string PassName = Pass.str();
675 std::string IrName = LLVMRustwrappedIrGetName(Ir);
676 BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str());
677 });
682678
683679 PIC.registerAfterAnalysisCallback(
684680 [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, llvm::Any Ir) {
......@@ -704,7 +700,7 @@ struct LLVMRustSanitizerOptions {
704700 bool SanitizeKCFI;
705701 bool SanitizeMemory;
706702 bool SanitizeMemoryRecover;
707 int SanitizeMemoryTrackOrigins;
703 int SanitizeMemoryTrackOrigins;
708704 bool SanitizeThread;
709705 bool SanitizeHWAddress;
710706 bool SanitizeHWAddressRecover;
......@@ -712,31 +708,25 @@ struct LLVMRustSanitizerOptions {
712708 bool SanitizeKernelAddressRecover;
713709};
714710
715extern "C" LLVMRustResult
716LLVMRustOptimize(
717 LLVMModuleRef ModuleRef,
718 LLVMTargetMachineRef TMRef,
719 LLVMRustPassBuilderOptLevel OptLevelRust,
720 LLVMRustOptStage OptStage,
721 bool IsLinkerPluginLTO,
722 bool NoPrepopulatePasses, bool VerifyIR, bool UseThinLTOBuffers,
723 bool MergeFunctions, bool UnrollLoops, bool SLPVectorize, bool LoopVectorize,
724 bool DisableSimplifyLibCalls, bool EmitLifetimeMarkers,
725 LLVMRustSanitizerOptions *SanitizerOptions,
726 const char *PGOGenPath, const char *PGOUsePath,
727 bool InstrumentCoverage, const char *InstrProfileOutput,
728 bool InstrumentGCOV,
711extern "C" LLVMRustResult LLVMRustOptimize(
712 LLVMModuleRef ModuleRef, LLVMTargetMachineRef TMRef,
713 LLVMRustPassBuilderOptLevel OptLevelRust, LLVMRustOptStage OptStage,
714 bool IsLinkerPluginLTO, bool NoPrepopulatePasses, bool VerifyIR,
715 bool UseThinLTOBuffers, bool MergeFunctions, bool UnrollLoops,
716 bool SLPVectorize, bool LoopVectorize, bool DisableSimplifyLibCalls,
717 bool EmitLifetimeMarkers, LLVMRustSanitizerOptions *SanitizerOptions,
718 const char *PGOGenPath, const char *PGOUsePath, bool InstrumentCoverage,
719 const char *InstrProfileOutput, bool InstrumentGCOV,
729720 const char *PGOSampleUsePath, bool DebugInfoForProfiling,
730 void* LlvmSelfProfiler,
721 void *LlvmSelfProfiler,
731722 LLVMRustSelfProfileBeforePassCallback BeforePassCallback,
732723 LLVMRustSelfProfileAfterPassCallback AfterPassCallback,
733 const char *ExtraPasses, size_t ExtraPassesLen,
734 const char *LLVMPlugins, size_t LLVMPluginsLen) {
724 const char *ExtraPasses, size_t ExtraPassesLen, const char *LLVMPlugins,
725 size_t LLVMPluginsLen) {
735726 Module *TheModule = unwrap(ModuleRef);
736727 TargetMachine *TM = unwrap(TMRef);
737728 OptimizationLevel OptLevel = fromRust(OptLevelRust);
738729
739
740730 PipelineTuningOptions PTO;
741731 PTO.LoopUnrolling = UnrollLoops;
742732 PTO.LoopInterleaving = UnrollLoops;
......@@ -751,38 +741,39 @@ LLVMRustOptimize(
751741 StandardInstrumentations SI(TheModule->getContext(), DebugPassManager);
752742 SI.registerCallbacks(PIC);
753743
754 if (LlvmSelfProfiler){
755 LLVMSelfProfileInitializeCallbacks(PIC,LlvmSelfProfiler,BeforePassCallback,AfterPassCallback);
744 if (LlvmSelfProfiler) {
745 LLVMSelfProfileInitializeCallbacks(PIC, LlvmSelfProfiler,
746 BeforePassCallback, AfterPassCallback);
756747 }
757748
758749 std::optional<PGOOptions> PGOOpt;
759750 auto FS = vfs::getRealFileSystem();
760751 if (PGOGenPath) {
761752 assert(!PGOUsePath && !PGOSampleUsePath);
762 PGOOpt = PGOOptions(PGOGenPath, "", "", "", FS,
763 PGOOptions::IRInstr, PGOOptions::NoCSAction,
753 PGOOpt = PGOOptions(PGOGenPath, "", "", "", FS, PGOOptions::IRInstr,
754 PGOOptions::NoCSAction,
764755#if LLVM_VERSION_GE(19, 0)
765756 PGOOptions::ColdFuncOpt::Default,
766757#endif
767758 DebugInfoForProfiling);
768759 } else if (PGOUsePath) {
769760 assert(!PGOSampleUsePath);
770 PGOOpt = PGOOptions(PGOUsePath, "", "", "", FS,
771 PGOOptions::IRUse, PGOOptions::NoCSAction,
761 PGOOpt = PGOOptions(PGOUsePath, "", "", "", FS, PGOOptions::IRUse,
762 PGOOptions::NoCSAction,
772763#if LLVM_VERSION_GE(19, 0)
773764 PGOOptions::ColdFuncOpt::Default,
774765#endif
775766 DebugInfoForProfiling);
776767 } else if (PGOSampleUsePath) {
777 PGOOpt = PGOOptions(PGOSampleUsePath, "", "", "", FS,
778 PGOOptions::SampleUse, PGOOptions::NoCSAction,
768 PGOOpt = PGOOptions(PGOSampleUsePath, "", "", "", FS, PGOOptions::SampleUse,
769 PGOOptions::NoCSAction,
779770#if LLVM_VERSION_GE(19, 0)
780771 PGOOptions::ColdFuncOpt::Default,
781772#endif
782773 DebugInfoForProfiling);
783774 } else if (DebugInfoForProfiling) {
784 PGOOpt = PGOOptions("", "", "", "", FS,
785 PGOOptions::NoAction, PGOOptions::NoCSAction,
775 PGOOpt = PGOOptions("", "", "", "", FS, PGOOptions::NoAction,
776 PGOOptions::NoCSAction,
786777#if LLVM_VERSION_GE(19, 0)
787778 PGOOptions::ColdFuncOpt::Default,
788779#endif
......@@ -799,7 +790,7 @@ LLVMRustOptimize(
799790 auto PluginsStr = StringRef(LLVMPlugins, LLVMPluginsLen);
800791 SmallVector<StringRef> Plugins;
801792 PluginsStr.split(Plugins, ',', -1, false);
802 for (auto PluginPath: Plugins) {
793 for (auto PluginPath : Plugins) {
803794 auto Plugin = PassPlugin::Load(PluginPath.str());
804795 if (!Plugin) {
805796 auto Err = Plugin.takeError();
......@@ -814,7 +805,8 @@ LLVMRustOptimize(
814805 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
815806
816807 Triple TargetTriple(TheModule->getTargetTriple());
817 std::unique_ptr<TargetLibraryInfoImpl> TLII(new TargetLibraryInfoImpl(TargetTriple));
808 std::unique_ptr<TargetLibraryInfoImpl> TLII(
809 new TargetLibraryInfoImpl(TargetTriple));
818810 if (DisableSimplifyLibCalls)
819811 TLII->disableAllFunctions();
820812 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
......@@ -825,58 +817,53 @@ LLVMRustOptimize(
825817 PB.registerLoopAnalyses(LAM);
826818 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
827819
828 // We manually collect pipeline callbacks so we can apply them at O0, where the
829 // PassBuilder does not create a pipeline.
820 // We manually collect pipeline callbacks so we can apply them at O0, where
821 // the PassBuilder does not create a pipeline.
830822 std::vector<std::function<void(ModulePassManager &, OptimizationLevel)>>
831823 PipelineStartEPCallbacks;
832824 std::vector<std::function<void(ModulePassManager &, OptimizationLevel)>>
833825 OptimizerLastEPCallbacks;
834826
835 if (!IsLinkerPluginLTO
836 && SanitizerOptions && SanitizerOptions->SanitizeCFI
837 && !NoPrepopulatePasses) {
827 if (!IsLinkerPluginLTO && SanitizerOptions && SanitizerOptions->SanitizeCFI &&
828 !NoPrepopulatePasses) {
838829 PipelineStartEPCallbacks.push_back(
839 [](ModulePassManager &MPM, OptimizationLevel Level) {
840 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
841 /*ImportSummary=*/nullptr,
842 /*DropTypeTests=*/false));
843 }
844 );
830 [](ModulePassManager &MPM, OptimizationLevel Level) {
831 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
832 /*ImportSummary=*/nullptr,
833 /*DropTypeTests=*/false));
834 });
845835 }
846836
847837 if (VerifyIR) {
848838 PipelineStartEPCallbacks.push_back(
849 [VerifyIR](ModulePassManager &MPM, OptimizationLevel Level) {
850 MPM.addPass(VerifierPass());
851 }
852 );
839 [VerifyIR](ModulePassManager &MPM, OptimizationLevel Level) {
840 MPM.addPass(VerifierPass());
841 });
853842 }
854843
855844 if (InstrumentGCOV) {
856845 PipelineStartEPCallbacks.push_back(
857 [](ModulePassManager &MPM, OptimizationLevel Level) {
858 MPM.addPass(GCOVProfilerPass(GCOVOptions::getDefault()));
859 }
860 );
846 [](ModulePassManager &MPM, OptimizationLevel Level) {
847 MPM.addPass(GCOVProfilerPass(GCOVOptions::getDefault()));
848 });
861849 }
862850
863851 if (InstrumentCoverage) {
864852 PipelineStartEPCallbacks.push_back(
865 [InstrProfileOutput](ModulePassManager &MPM, OptimizationLevel Level) {
866 InstrProfOptions Options;
867 if (InstrProfileOutput) {
868 Options.InstrProfileOutput = InstrProfileOutput;
869 }
870 // cargo run tests in multhreading mode by default
871 // so use atomics for coverage counters
872 Options.Atomic = true;
853 [InstrProfileOutput](ModulePassManager &MPM, OptimizationLevel Level) {
854 InstrProfOptions Options;
855 if (InstrProfileOutput) {
856 Options.InstrProfileOutput = InstrProfileOutput;
857 }
858 // cargo run tests in multhreading mode by default
859 // so use atomics for coverage counters
860 Options.Atomic = true;
873861#if LLVM_VERSION_GE(18, 0)
874 MPM.addPass(InstrProfilingLoweringPass(Options, false));
862 MPM.addPass(InstrProfilingLoweringPass(Options, false));
875863#else
876 MPM.addPass(InstrProfiling(Options, false));
864 MPM.addPass(InstrProfiling(Options, false));
877865#endif
878 }
879 );
866 });
880867 }
881868
882869 if (SanitizerOptions) {
......@@ -886,10 +873,9 @@ LLVMRustOptimize(
886873 SanitizerOptions->SanitizeDataFlowABIList +
887874 SanitizerOptions->SanitizeDataFlowABIListLen);
888875 OptimizerLastEPCallbacks.push_back(
889 [ABIListFiles](ModulePassManager &MPM, OptimizationLevel Level) {
890 MPM.addPass(DataFlowSanitizerPass(ABIListFiles));
891 }
892 );
876 [ABIListFiles](ModulePassManager &MPM, OptimizationLevel Level) {
877 MPM.addPass(DataFlowSanitizerPass(ABIListFiles));
878 });
893879 }
894880
895881 if (SanitizerOptions->SanitizeMemory) {
......@@ -899,54 +885,54 @@ LLVMRustOptimize(
899885 /*CompileKernel=*/false,
900886 /*EagerChecks=*/true);
901887 OptimizerLastEPCallbacks.push_back(
902 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
903 MPM.addPass(MemorySanitizerPass(Options));
904 }
905 );
888 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
889 MPM.addPass(MemorySanitizerPass(Options));
890 });
906891 }
907892
908893 if (SanitizerOptions->SanitizeThread) {
909 OptimizerLastEPCallbacks.push_back(
910 [](ModulePassManager &MPM, OptimizationLevel Level) {
911 MPM.addPass(ModuleThreadSanitizerPass());
912 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
913 }
914 );
894 OptimizerLastEPCallbacks.push_back([](ModulePassManager &MPM,
895 OptimizationLevel Level) {
896 MPM.addPass(ModuleThreadSanitizerPass());
897 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
898 });
915899 }
916900
917 if (SanitizerOptions->SanitizeAddress || SanitizerOptions->SanitizeKernelAddress) {
901 if (SanitizerOptions->SanitizeAddress ||
902 SanitizerOptions->SanitizeKernelAddress) {
918903 OptimizerLastEPCallbacks.push_back(
919 [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) {
920 auto CompileKernel = SanitizerOptions->SanitizeKernelAddress;
921 AddressSanitizerOptions opts = AddressSanitizerOptions{
922 CompileKernel,
923 SanitizerOptions->SanitizeAddressRecover
924 || SanitizerOptions->SanitizeKernelAddressRecover,
925 /*UseAfterScope=*/true,
926 AsanDetectStackUseAfterReturnMode::Runtime,
927 };
928 MPM.addPass(AddressSanitizerPass(opts));
929 }
930 );
904 [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) {
905 auto CompileKernel = SanitizerOptions->SanitizeKernelAddress;
906 AddressSanitizerOptions opts = AddressSanitizerOptions{
907 CompileKernel,
908 SanitizerOptions->SanitizeAddressRecover ||
909 SanitizerOptions->SanitizeKernelAddressRecover,
910 /*UseAfterScope=*/true,
911 AsanDetectStackUseAfterReturnMode::Runtime,
912 };
913 MPM.addPass(AddressSanitizerPass(opts));
914 });
931915 }
932916 if (SanitizerOptions->SanitizeHWAddress) {
933917 OptimizerLastEPCallbacks.push_back(
934 [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) {
935 HWAddressSanitizerOptions opts(
936 /*CompileKernel=*/false, SanitizerOptions->SanitizeHWAddressRecover,
937 /*DisableOptimization=*/false);
938 MPM.addPass(HWAddressSanitizerPass(opts));
939 }
940 );
918 [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) {
919 HWAddressSanitizerOptions opts(
920 /*CompileKernel=*/false,
921 SanitizerOptions->SanitizeHWAddressRecover,
922 /*DisableOptimization=*/false);
923 MPM.addPass(HWAddressSanitizerPass(opts));
924 });
941925 }
942926 }
943927
944928 ModulePassManager MPM;
945929 bool NeedThinLTOBufferPasses = UseThinLTOBuffers;
946930 if (!NoPrepopulatePasses) {
947 // The pre-link pipelines don't support O0 and require using buildO0DefaultPipeline() instead.
948 // At the same time, the LTO pipelines do support O0 and using them is required.
949 bool IsLTO = OptStage == LLVMRustOptStage::ThinLTO || OptStage == LLVMRustOptStage::FatLTO;
931 // The pre-link pipelines don't support O0 and require using
932 // buildO0DefaultPipeline() instead. At the same time, the LTO pipelines do
933 // support O0 and using them is required.
934 bool IsLTO = OptStage == LLVMRustOptStage::ThinLTO ||
935 OptStage == LLVMRustOptStage::FatLTO;
950936 if (OptLevel == OptimizationLevel::O0 && !IsLTO) {
951937 for (const auto &C : PipelineStartEPCallbacks)
952938 PB.registerPipelineStartEPCallback(C);
......@@ -993,7 +979,8 @@ LLVMRustOptimize(
993979 }
994980
995981 if (ExtraPassesLen) {
996 if (auto Err = PB.parsePassPipeline(MPM, StringRef(ExtraPasses, ExtraPassesLen))) {
982 if (auto Err =
983 PB.parsePassPipeline(MPM, StringRef(ExtraPasses, ExtraPassesLen))) {
997984 std::string ErrMsg = toString(std::move(Err));
998985 LLVMRustSetLastError(ErrMsg.c_str());
999986 return LLVMRustResult::Failure;
......@@ -1020,8 +1007,7 @@ LLVMRustOptimize(
10201007// * output buffer
10211008// * output buffer len
10221009// Returns len of demangled string, or 0 if demangle failed.
1023typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
1024
1010typedef size_t (*DemangleFn)(const char *, size_t, char *, size_t);
10251011
10261012namespace {
10271013
......@@ -1064,7 +1050,7 @@ public:
10641050 formatted_raw_ostream &OS) override {
10651051 StringRef Demangled = CallDemangle(F->getName());
10661052 if (Demangled.empty()) {
1067 return;
1053 return;
10681054 }
10691055
10701056 OS << "; " << Demangled << "\n";
......@@ -1077,7 +1063,7 @@ public:
10771063 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
10781064 Name = "call";
10791065 Value = CI->getCalledOperand();
1080 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
1066 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
10811067 Name = "invoke";
10821068 Value = II->getCalledOperand();
10831069 } else {
......@@ -1101,8 +1087,8 @@ public:
11011087
11021088} // namespace
11031089
1104extern "C" LLVMRustResult
1105LLVMRustPrintModule(LLVMModuleRef M, const char *Path, DemangleFn Demangle) {
1090extern "C" LLVMRustResult LLVMRustPrintModule(LLVMModuleRef M, const char *Path,
1091 DemangleFn Demangle) {
11061092 std::string ErrorInfo;
11071093 std::error_code EC;
11081094 auto OS = raw_fd_ostream(Path, EC, sys::fs::OF_None);
......@@ -1264,11 +1250,9 @@ getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
12641250// The main entry point for creating the global ThinLTO analysis. The structure
12651251// here is basically the same as before threads are spawned in the `run`
12661252// function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
1267extern "C" LLVMRustThinLTOData*
1268LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
1269 int num_modules,
1270 const char **preserved_symbols,
1271 int num_symbols) {
1253extern "C" LLVMRustThinLTOData *
1254LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, int num_modules,
1255 const char **preserved_symbols, int num_symbols) {
12721256 auto Ret = std::make_unique<LLVMRustThinLTOData>();
12731257
12741258 // Load each module's summary and merge it into one combined index
......@@ -1290,7 +1274,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
12901274 }
12911275
12921276 // Collect for each module the list of function it defines (GUID -> Summary)
1293 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
1277 Ret->Index.collectDefinedGVSummariesPerModule(
1278 Ret->ModuleToDefinedGVSummaries);
12941279
12951280 // Convert the preserved symbols set from string to GUID, this is then needed
12961281 // for internalization.
......@@ -1310,7 +1295,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13101295 // crate, so we need `ImportEnabled = false` to limit internalization.
13111296 // Otherwise, we sometimes lose `static` values -- see #60184.
13121297 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
1313 deadIsPrevailing, /* ImportEnabled = */ false);
1298 deadIsPrevailing,
1299 /* ImportEnabled = */ false);
13141300 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
13151301 // impacts the caching.
13161302 //
......@@ -1319,7 +1305,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13191305 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
13201306 for (auto &I : Ret->Index) {
13211307 if (I.second.SummaryList.size() > 1)
1322 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
1308 PrevailingCopy[I.first] =
1309 getFirstDefinitionForLinker(I.second.SummaryList);
13231310 }
13241311 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
13251312 const auto &Prevailing = PrevailingCopy.find(GUID);
......@@ -1327,13 +1314,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13271314 return true;
13281315 return Prevailing->second == S;
13291316 };
1330 ComputeCrossModuleImport(
1331 Ret->Index,
1332 Ret->ModuleToDefinedGVSummaries,
1333 isPrevailing,
1334 Ret->ImportLists,
1335 Ret->ExportLists
1336 );
1317 ComputeCrossModuleImport(Ret->Index, Ret->ModuleToDefinedGVSummaries,
1318 isPrevailing, Ret->ImportLists, Ret->ExportLists);
13371319
13381320 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
13391321 GlobalValue::GUID GUID,
......@@ -1345,8 +1327,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13451327 // formats. We probably could and should use ELF visibility scheme for many of
13461328 // our targets, however.
13471329 lto::Config conf;
1348 thinLTOResolvePrevailingInIndex(conf, Ret->Index, isPrevailing, recordNewLinkage,
1349 Ret->GUIDPreservedSymbols);
1330 thinLTOResolvePrevailingInIndex(conf, Ret->Index, isPrevailing,
1331 recordNewLinkage, Ret->GUIDPreservedSymbols);
13501332
13511333 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
13521334 // callback below. This callback below will dictate the linkage for all
......@@ -1355,7 +1337,7 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13551337 // linkage will stay as external, and internal will stay as internal.
13561338 std::set<GlobalValue::GUID> ExportedGUIDs;
13571339 for (auto &List : Ret->Index) {
1358 for (auto &GVS: List.second.SummaryList) {
1340 for (auto &GVS : List.second.SummaryList) {
13591341 if (GlobalValue::isLocalLinkage(GVS->linkage()))
13601342 continue;
13611343 auto GUID = GVS->getOriginalName();
......@@ -1366,16 +1348,15 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
13661348 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
13671349 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
13681350 return (ExportList != Ret->ExportLists.end() &&
1369 ExportList->second.count(VI)) ||
1370 ExportedGUIDs.count(VI.getGUID());
1351 ExportList->second.count(VI)) ||
1352 ExportedGUIDs.count(VI.getGUID());
13711353 };
13721354 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported, isPrevailing);
13731355
13741356 return Ret.release();
13751357}
13761358
1377extern "C" void
1378LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1359extern "C" void LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
13791360 delete Data;
13801361}
13811362
......@@ -1387,20 +1368,18 @@ LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
13871368// `ProcessThinLTOModule` function. Here they're split up into separate steps
13881369// so rustc can save off the intermediate bytecode between each step.
13891370
1390static bool
1391clearDSOLocalOnDeclarations(Module &Mod, TargetMachine &TM) {
1371static bool clearDSOLocalOnDeclarations(Module &Mod, TargetMachine &TM) {
13921372 // When linking an ELF shared object, dso_local should be dropped. We
13931373 // conservatively do this for -fpic.
1394 bool ClearDSOLocalOnDeclarations =
1395 TM.getTargetTriple().isOSBinFormatELF() &&
1396 TM.getRelocationModel() != Reloc::Static &&
1397 Mod.getPIELevel() == PIELevel::Default;
1374 bool ClearDSOLocalOnDeclarations = TM.getTargetTriple().isOSBinFormatELF() &&
1375 TM.getRelocationModel() != Reloc::Static &&
1376 Mod.getPIELevel() == PIELevel::Default;
13981377 return ClearDSOLocalOnDeclarations;
13991378}
14001379
1401extern "C" bool
1402LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M,
1403 LLVMTargetMachineRef TM) {
1380extern "C" bool LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data,
1381 LLVMModuleRef M,
1382 LLVMTargetMachineRef TM) {
14041383 Module &Mod = *unwrap(M);
14051384 TargetMachine &Target = *unwrap(TM);
14061385
......@@ -1415,24 +1394,28 @@ LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M,
14151394}
14161395
14171396extern "C" bool
1418LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1397LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data,
1398 LLVMModuleRef M) {
14191399 Module &Mod = *unwrap(M);
1420 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1400 const auto &DefinedGlobals =
1401 Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
14211402 thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
14221403 return true;
14231404}
14241405
14251406extern "C" bool
1426LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1407LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data,
1408 LLVMModuleRef M) {
14271409 Module &Mod = *unwrap(M);
1428 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1410 const auto &DefinedGlobals =
1411 Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
14291412 thinLTOInternalizeModule(Mod, DefinedGlobals);
14301413 return true;
14311414}
14321415
1433extern "C" bool
1434LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M,
1435 LLVMTargetMachineRef TM) {
1416extern "C" bool LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data,
1417 LLVMModuleRef M,
1418 LLVMTargetMachineRef TM) {
14361419 Module &Mod = *unwrap(M);
14371420 TargetMachine &Target = *unwrap(TM);
14381421
......@@ -1464,7 +1447,8 @@ LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M,
14641447 return Ret;
14651448 }
14661449
1467 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1450 auto *WasmCustomSections =
1451 (*MOrErr)->getNamedMetadata("wasm.custom_sections");
14681452 if (WasmCustomSections)
14691453 WasmCustomSections->eraseFromParent();
14701454
......@@ -1498,7 +1482,7 @@ struct LLVMRustThinLTOBuffer {
14981482 std::string thin_link_data;
14991483};
15001484
1501extern "C" LLVMRustThinLTOBuffer*
1485extern "C" LLVMRustThinLTOBuffer *
15021486LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) {
15031487 auto Ret = std::make_unique<LLVMRustThinLTOBuffer>();
15041488 {
......@@ -1520,7 +1504,8 @@ LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) {
15201504 // We only pass ThinLinkOS to be filled in if we want the summary,
15211505 // because otherwise LLVM does extra work and may double-emit some
15221506 // errors or warnings.
1523 MPM.addPass(ThinLTOBitcodeWriterPass(OS, emit_summary ? &ThinLinkOS : nullptr));
1507 MPM.addPass(
1508 ThinLTOBitcodeWriterPass(OS, emit_summary ? &ThinLinkOS : nullptr));
15241509 MPM.run(*unwrap(M), MAM);
15251510 } else {
15261511 WriteBitcodeToFile(*unwrap(M), OS);
......@@ -1530,12 +1515,11 @@ LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) {
15301515 return Ret.release();
15311516}
15321517
1533extern "C" void
1534LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1518extern "C" void LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
15351519 delete Buffer;
15361520}
15371521
1538extern "C" const void*
1522extern "C" const void *
15391523LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
15401524 return Buffer->data.data();
15411525}
......@@ -1545,7 +1529,7 @@ LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
15451529 return Buffer->data.length();
15461530}
15471531
1548extern "C" const void*
1532extern "C" const void *
15491533LLVMRustThinLTOBufferThinLinkDataPtr(const LLVMRustThinLTOBuffer *Buffer) {
15501534 return Buffer->thin_link_data.data();
15511535}
......@@ -1558,11 +1542,10 @@ LLVMRustThinLTOBufferThinLinkDataLen(const LLVMRustThinLTOBuffer *Buffer) {
15581542// This is what we used to parse upstream bitcode for actual ThinLTO
15591543// processing. We'll call this once per module optimized through ThinLTO, and
15601544// it'll be called concurrently on many threads.
1561extern "C" LLVMModuleRef
1562LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1563 const char *data,
1564 size_t len,
1565 const char *identifier) {
1545extern "C" LLVMModuleRef LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1546 const char *data,
1547 size_t len,
1548 const char *identifier) {
15661549 auto Data = StringRef(data, len);
15671550 auto Buffer = MemoryBufferRef(Data, identifier);
15681551 unwrap(Context)->enableDebugTypeODRUniquing();
......@@ -1614,8 +1597,9 @@ extern "C" const char *LLVMRustGetSliceFromObjectDataByName(const char *data,
16141597// of access globals, etc).
16151598// The precise details are determined by LLVM in `computeLTOCacheKey`, which is
16161599// used during the normal linker-plugin incremental thin-LTO process.
1617extern "C" void
1618LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, const char *ModId, LLVMRustThinLTOData *Data) {
1600extern "C" void LLVMRustComputeLTOCacheKey(RustStringRef KeyOut,
1601 const char *ModId,
1602 LLVMRustThinLTOData *Data) {
16191603 SmallString<40> Key;
16201604 llvm::lto::Config conf;
16211605 const auto &ImportList = Data->ImportLists.lookup(ModId);
......@@ -1633,9 +1617,9 @@ LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, const char *ModId, LLVMRustThin
16331617 CfiFunctionDecls.insert(
16341618 GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
16351619
1636 llvm::computeLTOCacheKey(Key, conf, Data->Index, ModId,
1637 ImportList, ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls
1638 );
1620 llvm::computeLTOCacheKey(Key, conf, Data->Index, ModId, ImportList,
1621 ExportList, ResolvedODR, DefinedGlobals,
1622 CfiFunctionDefs, CfiFunctionDecls);
16391623
16401624 LLVMRustStringWriteImpl(KeyOut, Key.c_str(), Key.size());
16411625}
compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp+497-530
......@@ -1,5 +1,6 @@
11#include "LLVMWrapper.h"
22#include "llvm/ADT/Statistic.h"
3#include "llvm/Bitcode/BitcodeWriter.h"
34#include "llvm/IR/DebugInfoMetadata.h"
45#include "llvm/IR/DiagnosticHandler.h"
56#include "llvm/IR/DiagnosticInfo.h"
......@@ -11,17 +12,16 @@
1112#include "llvm/IR/LLVMRemarkStreamer.h"
1213#include "llvm/IR/Mangler.h"
1314#include "llvm/IR/Value.h"
14#include "llvm/Remarks/RemarkStreamer.h"
15#include "llvm/Remarks/RemarkSerializer.h"
16#include "llvm/Remarks/RemarkFormat.h"
17#include "llvm/Support/ToolOutputFile.h"
18#include "llvm/Support/ModRef.h"
1915#include "llvm/Object/Archive.h"
2016#include "llvm/Object/COFFImportFile.h"
2117#include "llvm/Object/ObjectFile.h"
2218#include "llvm/Pass.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
19#include "llvm/Remarks/RemarkFormat.h"
20#include "llvm/Remarks/RemarkSerializer.h"
21#include "llvm/Remarks/RemarkStreamer.h"
22#include "llvm/Support/ModRef.h"
2423#include "llvm/Support/Signals.h"
24#include "llvm/Support/ToolOutputFile.h"
2525
2626#include <iostream>
2727
......@@ -71,12 +71,12 @@ static LLVM_THREAD_LOCAL char *LastError;
7171// Custom error handler for fatal LLVM errors.
7272//
7373// Notably it exits the process with code 101, unlike LLVM's default of 1.
74static void FatalErrorHandler(void *UserData,
75 const char* Reason,
74static void FatalErrorHandler(void *UserData, const char *Reason,
7675 bool GenCrashDiag) {
7776 // Once upon a time we emitted "LLVM ERROR:" specifically to mimic LLVM. Then,
78 // we developed crater and other tools which only expose logs, not error codes.
79 // Use a more greppable prefix that will still match the "LLVM ERROR:" prefix.
77 // we developed crater and other tools which only expose logs, not error
78 // codes. Use a more greppable prefix that will still match the "LLVM ERROR:"
79 // prefix.
8080 std::cerr << "rustc-LLVM ERROR: " << Reason << std::endl;
8181
8282 // Since this error handler exits the process, we have to run any cleanup that
......@@ -99,8 +99,7 @@ static void FatalErrorHandler(void *UserData,
9999//
100100// It aborts the process without any further allocations, similar to LLVM's
101101// default except that may be configured to `throw std::bad_alloc()` instead.
102static void BadAllocErrorHandler(void *UserData,
103 const char* Reason,
102static void BadAllocErrorHandler(void *UserData, const char *Reason,
104103 bool GenCrashDiag) {
105104 const char *OOM = "rustc-LLVM ERROR: out of memory\n";
106105 (void)!::write(2, OOM, strlen(OOM));
......@@ -190,7 +189,8 @@ static CallInst::TailCallKind fromRust(LLVMRustTailCallKind Kind) {
190189 }
191190}
192191
193extern "C" void LLVMRustSetTailCallKind(LLVMValueRef Call, LLVMRustTailCallKind TCK) {
192extern "C" void LLVMRustSetTailCallKind(LLVMValueRef Call,
193 LLVMRustTailCallKind TCK) {
194194 unwrap<CallInst>(Call)->setTailCallKind(fromRust(TCK));
195195}
196196
......@@ -201,12 +201,13 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
201201 return wrap(unwrap(M)
202202 ->getOrInsertFunction(StringRef(Name, NameLen),
203203 unwrap<FunctionType>(FunctionTy))
204 .getCallee()
205 );
204 .getCallee());
206205}
207206
208extern "C" LLVMValueRef
209LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLVMTypeRef Ty) {
207extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M,
208 const char *Name,
209 size_t NameLen,
210 LLVMTypeRef Ty) {
210211 Module *Mod = unwrap(M);
211212 auto NameRef = StringRef(Name, NameLen);
212213
......@@ -221,13 +222,10 @@ LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLV
221222 return wrap(GV);
222223}
223224
224extern "C" LLVMValueRef
225LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) {
226 return wrap(new GlobalVariable(*unwrap(M),
227 unwrap(Ty),
228 false,
229 GlobalValue::PrivateLinkage,
230 nullptr));
225extern "C" LLVMValueRef LLVMRustInsertPrivateGlobal(LLVMModuleRef M,
226 LLVMTypeRef Ty) {
227 return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false,
228 GlobalValue::PrivateLinkage, nullptr));
231229}
232230
233231static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
......@@ -326,8 +324,9 @@ static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
326324 report_fatal_error("bad AttributeKind");
327325}
328326
329template<typename T> static inline void AddAttributes(T *t, unsigned Index,
330 LLVMAttributeRef *Attrs, size_t AttrsLen) {
327template <typename T>
328static inline void AddAttributes(T *t, unsigned Index, LLVMAttributeRef *Attrs,
329 size_t AttrsLen) {
331330 AttributeList PAL = t->getAttributes();
332331 auto B = AttrBuilder(t->getContext());
333332 for (LLVMAttributeRef Attr : ArrayRef<LLVMAttributeRef>(Attrs, AttrsLen))
......@@ -337,19 +336,22 @@ template<typename T> static inline void AddAttributes(T *t, unsigned Index,
337336}
338337
339338extern "C" void LLVMRustAddFunctionAttributes(LLVMValueRef Fn, unsigned Index,
340 LLVMAttributeRef *Attrs, size_t AttrsLen) {
339 LLVMAttributeRef *Attrs,
340 size_t AttrsLen) {
341341 Function *F = unwrap<Function>(Fn);
342342 AddAttributes(F, Index, Attrs, AttrsLen);
343343}
344344
345extern "C" void LLVMRustAddCallSiteAttributes(LLVMValueRef Instr, unsigned Index,
346 LLVMAttributeRef *Attrs, size_t AttrsLen) {
345extern "C" void LLVMRustAddCallSiteAttributes(LLVMValueRef Instr,
346 unsigned Index,
347 LLVMAttributeRef *Attrs,
348 size_t AttrsLen) {
347349 CallBase *Call = unwrap<CallBase>(Instr);
348350 AddAttributes(Call, Index, Attrs, AttrsLen);
349351}
350352
351extern "C" LLVMAttributeRef LLVMRustCreateAttrNoValue(LLVMContextRef C,
352 LLVMRustAttribute RustAttr) {
353extern "C" LLVMAttributeRef
354LLVMRustCreateAttrNoValue(LLVMContextRef C, LLVMRustAttribute RustAttr) {
353355 return wrap(Attribute::get(*unwrap(C), fromRust(RustAttr)));
354356}
355357
......@@ -363,30 +365,36 @@ extern "C" LLVMAttributeRef LLVMRustCreateDereferenceableAttr(LLVMContextRef C,
363365 return wrap(Attribute::getWithDereferenceableBytes(*unwrap(C), Bytes));
364366}
365367
366extern "C" LLVMAttributeRef LLVMRustCreateDereferenceableOrNullAttr(LLVMContextRef C,
367 uint64_t Bytes) {
368extern "C" LLVMAttributeRef
369LLVMRustCreateDereferenceableOrNullAttr(LLVMContextRef C, uint64_t Bytes) {
368370 return wrap(Attribute::getWithDereferenceableOrNullBytes(*unwrap(C), Bytes));
369371}
370372
371extern "C" LLVMAttributeRef LLVMRustCreateByValAttr(LLVMContextRef C, LLVMTypeRef Ty) {
373extern "C" LLVMAttributeRef LLVMRustCreateByValAttr(LLVMContextRef C,
374 LLVMTypeRef Ty) {
372375 return wrap(Attribute::getWithByValType(*unwrap(C), unwrap(Ty)));
373376}
374377
375extern "C" LLVMAttributeRef LLVMRustCreateStructRetAttr(LLVMContextRef C, LLVMTypeRef Ty) {
378extern "C" LLVMAttributeRef LLVMRustCreateStructRetAttr(LLVMContextRef C,
379 LLVMTypeRef Ty) {
376380 return wrap(Attribute::getWithStructRetType(*unwrap(C), unwrap(Ty)));
377381}
378382
379extern "C" LLVMAttributeRef LLVMRustCreateElementTypeAttr(LLVMContextRef C, LLVMTypeRef Ty) {
383extern "C" LLVMAttributeRef LLVMRustCreateElementTypeAttr(LLVMContextRef C,
384 LLVMTypeRef Ty) {
380385 return wrap(Attribute::get(*unwrap(C), Attribute::ElementType, unwrap(Ty)));
381386}
382387
383extern "C" LLVMAttributeRef LLVMRustCreateUWTableAttr(LLVMContextRef C, bool Async) {
388extern "C" LLVMAttributeRef LLVMRustCreateUWTableAttr(LLVMContextRef C,
389 bool Async) {
384390 return wrap(Attribute::getWithUWTableKind(
385391 *unwrap(C), Async ? UWTableKind::Async : UWTableKind::Sync));
386392}
387393
388extern "C" LLVMAttributeRef LLVMRustCreateAllocSizeAttr(LLVMContextRef C, uint32_t ElementSizeArg) {
389 return wrap(Attribute::getWithAllocSizeArgs(*unwrap(C), ElementSizeArg, std::nullopt));
394extern "C" LLVMAttributeRef
395LLVMRustCreateAllocSizeAttr(LLVMContextRef C, uint32_t ElementSizeArg) {
396 return wrap(Attribute::getWithAllocSizeArgs(*unwrap(C), ElementSizeArg,
397 std::nullopt));
390398}
391399
392400// These values **must** match ffi::AllocKindFlags.
......@@ -403,12 +411,15 @@ enum class LLVMRustAllocKindFlags : uint64_t {
403411 Aligned = 1 << 5,
404412};
405413
406static LLVMRustAllocKindFlags operator&(LLVMRustAllocKindFlags A, LLVMRustAllocKindFlags B) {
414static LLVMRustAllocKindFlags operator&(LLVMRustAllocKindFlags A,
415 LLVMRustAllocKindFlags B) {
407416 return static_cast<LLVMRustAllocKindFlags>(static_cast<uint64_t>(A) &
408 static_cast<uint64_t>(B));
417 static_cast<uint64_t>(B));
409418}
410419
411static bool isSet(LLVMRustAllocKindFlags F) { return F != LLVMRustAllocKindFlags::Unknown; }
420static bool isSet(LLVMRustAllocKindFlags F) {
421 return F != LLVMRustAllocKindFlags::Unknown;
422}
412423
413424static llvm::AllocFnKind allocKindFromRust(LLVMRustAllocKindFlags F) {
414425 llvm::AllocFnKind AFK = llvm::AllocFnKind::Unknown;
......@@ -433,40 +444,47 @@ static llvm::AllocFnKind allocKindFromRust(LLVMRustAllocKindFlags F) {
433444 return AFK;
434445}
435446
436extern "C" LLVMAttributeRef LLVMRustCreateAllocKindAttr(LLVMContextRef C, uint64_t AllocKindArg) {
437 return wrap(Attribute::get(*unwrap(C), Attribute::AllocKind,
438 static_cast<uint64_t>(allocKindFromRust(static_cast<LLVMRustAllocKindFlags>(AllocKindArg)))));
447extern "C" LLVMAttributeRef LLVMRustCreateAllocKindAttr(LLVMContextRef C,
448 uint64_t AllocKindArg) {
449 return wrap(
450 Attribute::get(*unwrap(C), Attribute::AllocKind,
451 static_cast<uint64_t>(allocKindFromRust(
452 static_cast<LLVMRustAllocKindFlags>(AllocKindArg)))));
439453}
440454
441455// Simplified representation of `MemoryEffects` across the FFI boundary.
442456//
443// Each variant corresponds to one of the static factory methods on `MemoryEffects`.
457// Each variant corresponds to one of the static factory methods on
458// `MemoryEffects`.
444459enum class LLVMRustMemoryEffects {
445460 None,
446461 ReadOnly,
447462 InaccessibleMemOnly,
448463};
449464
450extern "C" LLVMAttributeRef LLVMRustCreateMemoryEffectsAttr(LLVMContextRef C,
451 LLVMRustMemoryEffects Effects) {
465extern "C" LLVMAttributeRef
466LLVMRustCreateMemoryEffectsAttr(LLVMContextRef C,
467 LLVMRustMemoryEffects Effects) {
452468 switch (Effects) {
453 case LLVMRustMemoryEffects::None:
454 return wrap(Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::none()));
455 case LLVMRustMemoryEffects::ReadOnly:
456 return wrap(Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::readOnly()));
457 case LLVMRustMemoryEffects::InaccessibleMemOnly:
458 return wrap(Attribute::getWithMemoryEffects(*unwrap(C),
459 MemoryEffects::inaccessibleMemOnly()));
460 default:
461 report_fatal_error("bad MemoryEffects.");
462 }
463}
464
465// Enable all fast-math flags, including those which will cause floating-point operations
466// to return poison for some well-defined inputs. This function can only be used to build
467// unsafe Rust intrinsics. That unsafety does permit additional optimizations, but at the
468// time of writing, their value is not well-understood relative to those enabled by
469// LLVMRustSetAlgebraicMath.
469 case LLVMRustMemoryEffects::None:
470 return wrap(
471 Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::none()));
472 case LLVMRustMemoryEffects::ReadOnly:
473 return wrap(
474 Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::readOnly()));
475 case LLVMRustMemoryEffects::InaccessibleMemOnly:
476 return wrap(Attribute::getWithMemoryEffects(
477 *unwrap(C), MemoryEffects::inaccessibleMemOnly()));
478 default:
479 report_fatal_error("bad MemoryEffects.");
480 }
481}
482
483// Enable all fast-math flags, including those which will cause floating-point
484// operations to return poison for some well-defined inputs. This function can
485// only be used to build unsafe Rust intrinsics. That unsafety does permit
486// additional optimizations, but at the time of writing, their value is not
487// well-understood relative to those enabled by LLVMRustSetAlgebraicMath.
470488//
471489// https://llvm.org/docs/LangRef.html#fast-math-flags
472490extern "C" void LLVMRustSetFastMath(LLVMValueRef V) {
......@@ -475,14 +493,12 @@ extern "C" void LLVMRustSetFastMath(LLVMValueRef V) {
475493 }
476494}
477495
478// Enable fast-math flags which permit algebraic transformations that are not allowed by
479// IEEE floating point. For example:
480// a + (b + c) = (a + b) + c
481// and
482// a / b = a * (1 / b)
483// Note that this does NOT enable any flags which can cause a floating-point operation on
484// well-defined inputs to return poison, and therefore this function can be used to build
485// safe Rust intrinsics (such as fadd_algebraic).
496// Enable fast-math flags which permit algebraic transformations that are not
497// allowed by IEEE floating point. For example: a + (b + c) = (a + b) + c and a
498// / b = a * (1 / b) Note that this does NOT enable any flags which can cause a
499// floating-point operation on well-defined inputs to return poison, and
500// therefore this function can be used to build safe Rust intrinsics (such as
501// fadd_algebraic).
486502//
487503// https://llvm.org/docs/LangRef.html#fast-math-flags
488504extern "C" void LLVMRustSetAlgebraicMath(LLVMValueRef V) {
......@@ -497,9 +513,9 @@ extern "C" void LLVMRustSetAlgebraicMath(LLVMValueRef V) {
497513// Enable the reassoc fast-math flag, allowing transformations that pretend
498514// floating-point addition and multiplication are associative.
499515//
500// Note that this does NOT enable any flags which can cause a floating-point operation on
501// well-defined inputs to return poison, and therefore this function can be used to build
502// safe Rust intrinsics (such as fadd_algebraic).
516// Note that this does NOT enable any flags which can cause a floating-point
517// operation on well-defined inputs to return poison, and therefore this
518// function can be used to build safe Rust intrinsics (such as fadd_algebraic).
503519//
504520// https://llvm.org/docs/LangRef.html#fast-math-flags
505521extern "C" void LLVMRustSetAllowReassoc(LLVMValueRef V) {
......@@ -547,11 +563,10 @@ LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString, size_t AsmStringLen,
547563 char *Constraints, size_t ConstraintsLen,
548564 LLVMBool HasSideEffects, LLVMBool IsAlignStack,
549565 LLVMRustAsmDialect Dialect, LLVMBool CanThrow) {
550 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty),
551 StringRef(AsmString, AsmStringLen),
552 StringRef(Constraints, ConstraintsLen),
553 HasSideEffects, IsAlignStack,
554 fromRust(Dialect), CanThrow));
566 return wrap(InlineAsm::get(
567 unwrap<FunctionType>(Ty), StringRef(AsmString, AsmStringLen),
568 StringRef(Constraints, ConstraintsLen), HasSideEffects, IsAlignStack,
569 fromRust(Dialect), CanThrow));
555570}
556571
557572extern "C" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty, char *Constraints,
......@@ -705,19 +720,22 @@ enum class LLVMRustDISPFlags : uint32_t {
705720
706721inline LLVMRustDISPFlags operator&(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
707722 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) &
708 static_cast<uint32_t>(B));
723 static_cast<uint32_t>(B));
709724}
710725
711726inline LLVMRustDISPFlags operator|(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
712727 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) |
713 static_cast<uint32_t>(B));
728 static_cast<uint32_t>(B));
714729}
715730
716inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, LLVMRustDISPFlags B) {
731inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A,
732 LLVMRustDISPFlags B) {
717733 return A = A | B;
718734}
719735
720inline bool isSet(LLVMRustDISPFlags F) { return F != LLVMRustDISPFlags::SPFlagZero; }
736inline bool isSet(LLVMRustDISPFlags F) {
737 return F != LLVMRustDISPFlags::SPFlagZero;
738}
721739
722740inline LLVMRustDISPFlags virtuality(LLVMRustDISPFlags F) {
723741 return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(F) & 0x3);
......@@ -761,7 +779,8 @@ enum class LLVMRustDebugEmissionKind {
761779 DebugDirectivesOnly,
762780};
763781
764static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) {
782static DICompileUnit::DebugEmissionKind
783fromRust(LLVMRustDebugEmissionKind Kind) {
765784 switch (Kind) {
766785 case LLVMRustDebugEmissionKind::NoDebug:
767786 return DICompileUnit::DebugEmissionKind::NoDebug;
......@@ -777,12 +796,13 @@ static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind)
777796}
778797
779798enum class LLVMRustDebugNameTableKind {
780 Default,
781 GNU,
782 None,
799 Default,
800 GNU,
801 None,
783802};
784803
785static DICompileUnit::DebugNameTableKind fromRust(LLVMRustDebugNameTableKind Kind) {
804static DICompileUnit::DebugNameTableKind
805fromRust(LLVMRustDebugNameTableKind Kind) {
786806 switch (Kind) {
787807 case LLVMRustDebugNameTableKind::Default:
788808 return DICompileUnit::DebugNameTableKind::Default;
......@@ -827,22 +847,18 @@ extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
827847
828848extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
829849
830extern "C" void LLVMRustAddModuleFlagU32(
831 LLVMModuleRef M,
832 Module::ModFlagBehavior MergeBehavior,
833 const char *Name,
834 uint32_t Value) {
850extern "C" void LLVMRustAddModuleFlagU32(LLVMModuleRef M,
851 Module::ModFlagBehavior MergeBehavior,
852 const char *Name, uint32_t Value) {
835853 unwrap(M)->addModuleFlag(MergeBehavior, Name, Value);
836854}
837855
838856extern "C" void LLVMRustAddModuleFlagString(
839 LLVMModuleRef M,
840 Module::ModFlagBehavior MergeBehavior,
841 const char *Name,
842 const char *Value,
843 size_t ValueLen) {
844 unwrap(M)->addModuleFlag(MergeBehavior, Name,
845 MDString::get(unwrap(M)->getContext(), StringRef(Value, ValueLen)));
857 LLVMModuleRef M, Module::ModFlagBehavior MergeBehavior, const char *Name,
858 const char *Value, size_t ValueLen) {
859 unwrap(M)->addModuleFlag(
860 MergeBehavior, Name,
861 MDString::get(unwrap(M)->getContext(), StringRef(Value, ValueLen)));
846862}
847863
848864extern "C" bool LLVMRustHasModuleFlag(LLVMModuleRef M, const char *Name,
......@@ -850,8 +866,8 @@ extern "C" bool LLVMRustHasModuleFlag(LLVMModuleRef M, const char *Name,
850866 return unwrap(M)->getModuleFlag(StringRef(Name, Len)) != nullptr;
851867}
852868
853extern "C" void LLVMRustGlobalAddMetadata(
854 LLVMValueRef Global, unsigned Kind, LLVMMetadataRef MD) {
869extern "C" void LLVMRustGlobalAddMetadata(LLVMValueRef Global, unsigned Kind,
870 LLVMMetadataRef MD) {
855871 unwrap<GlobalObject>(Global)->addMetadata(Kind, *unwrap<MDNode>(MD));
856872}
857873
......@@ -870,33 +886,29 @@ extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
870886extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
871887 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
872888 const char *Producer, size_t ProducerLen, bool isOptimized,
873 const char *Flags, unsigned RuntimeVer,
874 const char *SplitName, size_t SplitNameLen,
875 LLVMRustDebugEmissionKind Kind,
876 uint64_t DWOId, bool SplitDebugInlining,
877 LLVMRustDebugNameTableKind TableKind) {
889 const char *Flags, unsigned RuntimeVer, const char *SplitName,
890 size_t SplitNameLen, LLVMRustDebugEmissionKind Kind, uint64_t DWOId,
891 bool SplitDebugInlining, LLVMRustDebugNameTableKind TableKind) {
878892 auto *File = unwrapDI<DIFile>(FileRef);
879893
880 return wrap(Builder->createCompileUnit(Lang, File, StringRef(Producer, ProducerLen),
881 isOptimized, Flags, RuntimeVer,
882 StringRef(SplitName, SplitNameLen),
883 fromRust(Kind), DWOId, SplitDebugInlining,
884 false, fromRust(TableKind)));
894 return wrap(Builder->createCompileUnit(
895 Lang, File, StringRef(Producer, ProducerLen), isOptimized, Flags,
896 RuntimeVer, StringRef(SplitName, SplitNameLen), fromRust(Kind), DWOId,
897 SplitDebugInlining, false, fromRust(TableKind)));
885898}
886899
887extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFile(
888 LLVMRustDIBuilderRef Builder,
889 const char *Filename, size_t FilenameLen,
890 const char *Directory, size_t DirectoryLen, LLVMRustChecksumKind CSKind,
891 const char *Checksum, size_t ChecksumLen) {
900extern "C" LLVMMetadataRef
901LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
902 size_t FilenameLen, const char *Directory,
903 size_t DirectoryLen, LLVMRustChecksumKind CSKind,
904 const char *Checksum, size_t ChecksumLen) {
892905
893906 std::optional<DIFile::ChecksumKind> llvmCSKind = fromRust(CSKind);
894907 std::optional<DIFile::ChecksumInfo<StringRef>> CSInfo{};
895908 if (llvmCSKind)
896909 CSInfo.emplace(*llvmCSKind, StringRef{Checksum, ChecksumLen});
897910 return wrap(Builder->createFile(StringRef(Filename, FilenameLen),
898 StringRef(Directory, DirectoryLen),
899 CSInfo));
911 StringRef(Directory, DirectoryLen), CSInfo));
900912}
901913
902914extern "C" LLVMMetadataRef
......@@ -907,63 +919,59 @@ LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
907919}
908920
909921extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
910 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
911 const char *Name, size_t NameLen,
912 const char *LinkageName, size_t LinkageNameLen,
913 LLVMMetadataRef File, unsigned LineNo,
914 LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags,
915 LLVMRustDISPFlags SPFlags, LLVMValueRef MaybeFn, LLVMMetadataRef TParam,
916 LLVMMetadataRef Decl) {
922 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
923 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
924 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
925 unsigned ScopeLine, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags,
926 LLVMValueRef MaybeFn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
917927 DITemplateParameterArray TParams =
918928 DITemplateParameterArray(unwrap<MDTuple>(TParam));
919929 DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags);
920930 DINode::DIFlags llvmFlags = fromRust(Flags);
921931 DISubprogram *Sub = Builder->createFunction(
922 unwrapDI<DIScope>(Scope),
923 StringRef(Name, NameLen),
924 StringRef(LinkageName, LinkageNameLen),
925 unwrapDI<DIFile>(File), LineNo,
926 unwrapDI<DISubroutineType>(Ty), ScopeLine, llvmFlags,
927 llvmSPFlags, TParams, unwrapDIPtr<DISubprogram>(Decl));
932 unwrapDI<DIScope>(Scope), StringRef(Name, NameLen),
933 StringRef(LinkageName, LinkageNameLen), unwrapDI<DIFile>(File), LineNo,
934 unwrapDI<DISubroutineType>(Ty), ScopeLine, llvmFlags, llvmSPFlags,
935 TParams, unwrapDIPtr<DISubprogram>(Decl));
928936 if (MaybeFn)
929937 unwrap<Function>(MaybeFn)->setSubprogram(Sub);
930938 return wrap(Sub);
931939}
932940
933941extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMethod(
934 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
935 const char *Name, size_t NameLen,
936 const char *LinkageName, size_t LinkageNameLen,
937 LLVMMetadataRef File, unsigned LineNo,
938 LLVMMetadataRef Ty, LLVMRustDIFlags Flags,
939 LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) {
942 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
943 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
944 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
945 LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) {
940946 DITemplateParameterArray TParams =
941947 DITemplateParameterArray(unwrap<MDTuple>(TParam));
942948 DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags);
943949 DINode::DIFlags llvmFlags = fromRust(Flags);
944950 DISubprogram *Sub = Builder->createMethod(
945 unwrapDI<DIScope>(Scope),
946 StringRef(Name, NameLen),
947 StringRef(LinkageName, LinkageNameLen),
948 unwrapDI<DIFile>(File), LineNo,
949 unwrapDI<DISubroutineType>(Ty),
950 0, 0, nullptr, // VTable params aren't used
951 unwrapDI<DIScope>(Scope), StringRef(Name, NameLen),
952 StringRef(LinkageName, LinkageNameLen), unwrapDI<DIFile>(File), LineNo,
953 unwrapDI<DISubroutineType>(Ty), 0, 0,
954 nullptr, // VTable params aren't used
951955 llvmFlags, llvmSPFlags, TParams);
952956 return wrap(Sub);
953957}
954958
955extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType(
956 LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen,
957 uint64_t SizeInBits, unsigned Encoding) {
958 return wrap(Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding));
959extern "C" LLVMMetadataRef
960LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
961 size_t NameLen, uint64_t SizeInBits,
962 unsigned Encoding) {
963 return wrap(
964 Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding));
959965}
960966
961extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTypedef(
962 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Type, const char *Name, size_t NameLen,
963 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Scope) {
967extern "C" LLVMMetadataRef
968LLVMRustDIBuilderCreateTypedef(LLVMRustDIBuilderRef Builder,
969 LLVMMetadataRef Type, const char *Name,
970 size_t NameLen, LLVMMetadataRef File,
971 unsigned LineNo, LLVMMetadataRef Scope) {
964972 return wrap(Builder->createTypedef(
965 unwrap<DIType>(Type), StringRef(Name, NameLen), unwrap<DIFile>(File),
966 LineNo, unwrapDIPtr<DIScope>(Scope)));
973 unwrap<DIType>(Type), StringRef(Name, NameLen), unwrap<DIFile>(File),
974 LineNo, unwrapDIPtr<DIScope>(Scope)));
967975}
968976
969977extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
......@@ -971,118 +979,98 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
971979 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
972980 const char *Name, size_t NameLen) {
973981 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
974 SizeInBits, AlignInBits,
975 AddressSpace,
982 SizeInBits, AlignInBits, AddressSpace,
976983 StringRef(Name, NameLen)));
977984}
978985
979986extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
980 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
981 const char *Name, size_t NameLen,
982 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
983 uint32_t AlignInBits, LLVMRustDIFlags Flags,
984 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
985 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
986 const char *UniqueId, size_t UniqueIdLen) {
987 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
988 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
989 uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags,
990 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements, unsigned RunTimeLang,
991 LLVMMetadataRef VTableHolder, const char *UniqueId, size_t UniqueIdLen) {
987992 return wrap(Builder->createStructType(
988993 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
989 unwrapDI<DIFile>(File), LineNumber,
990 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
994 unwrapDI<DIFile>(File), LineNumber, SizeInBits, AlignInBits,
995 fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
991996 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
992997 unwrapDI<DIType>(VTableHolder), StringRef(UniqueId, UniqueIdLen)));
993998}
994999
9951000extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart(
996 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
997 const char *Name, size_t NameLen,
998 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
999 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator,
1000 LLVMMetadataRef Elements, const char *UniqueId, size_t UniqueIdLen) {
1001 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1002 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1003 uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags,
1004 LLVMMetadataRef Discriminator, LLVMMetadataRef Elements,
1005 const char *UniqueId, size_t UniqueIdLen) {
10011006 return wrap(Builder->createVariantPart(
10021007 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1003 unwrapDI<DIFile>(File), LineNumber,
1004 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIDerivedType>(Discriminator),
1005 DINodeArray(unwrapDI<MDTuple>(Elements)), StringRef(UniqueId, UniqueIdLen)));
1008 unwrapDI<DIFile>(File), LineNumber, SizeInBits, AlignInBits,
1009 fromRust(Flags), unwrapDI<DIDerivedType>(Discriminator),
1010 DINodeArray(unwrapDI<MDTuple>(Elements)),
1011 StringRef(UniqueId, UniqueIdLen)));
10061012}
10071013
10081014extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
1009 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1010 const char *Name, size_t NameLen,
1011 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1015 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1016 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
10121017 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
10131018 LLVMMetadataRef Ty) {
1014 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope),
1015 StringRef(Name, NameLen),
1016 unwrapDI<DIFile>(File), LineNo,
1017 SizeInBits, AlignInBits, OffsetInBits,
1018 fromRust(Flags), unwrapDI<DIType>(Ty)));
1019 return wrap(Builder->createMemberType(
1020 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1021 unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits, OffsetInBits,
1022 fromRust(Flags), unwrapDI<DIType>(Ty)));
10191023}
10201024
10211025extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType(
1022 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1023 const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo,
1024 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant,
1026 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1027 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1028 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant,
10251029 LLVMRustDIFlags Flags, LLVMMetadataRef Ty) {
1026 llvm::ConstantInt* D = nullptr;
1030 llvm::ConstantInt *D = nullptr;
10271031 if (Discriminant) {
10281032 D = unwrap<llvm::ConstantInt>(Discriminant);
10291033 }
1030 return wrap(Builder->createVariantMemberType(unwrapDI<DIDescriptor>(Scope),
1031 StringRef(Name, NameLen),
1032 unwrapDI<DIFile>(File), LineNo,
1033 SizeInBits, AlignInBits, OffsetInBits, D,
1034 fromRust(Flags), unwrapDI<DIType>(Ty)));
1034 return wrap(Builder->createVariantMemberType(
1035 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1036 unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, D,
1037 fromRust(Flags), unwrapDI<DIType>(Ty)));
10351038}
10361039
10371040extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticMemberType(
1038 LLVMRustDIBuilderRef Builder,
1039 LLVMMetadataRef Scope,
1040 const char *Name,
1041 size_t NameLen,
1042 LLVMMetadataRef File,
1043 unsigned LineNo,
1044 LLVMMetadataRef Ty,
1045 LLVMRustDIFlags Flags,
1046 LLVMValueRef val,
1047 uint32_t AlignInBits
1048) {
1041 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1042 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1043 LLVMRustDIFlags Flags, LLVMValueRef val, uint32_t AlignInBits) {
10491044 return wrap(Builder->createStaticMemberType(
1050 unwrapDI<DIDescriptor>(Scope),
1051 StringRef(Name, NameLen),
1052 unwrapDI<DIFile>(File),
1053 LineNo,
1054 unwrapDI<DIType>(Ty),
1055 fromRust(Flags),
1056 unwrap<llvm::ConstantInt>(val),
1045 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1046 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), fromRust(Flags),
1047 unwrap<llvm::ConstantInt>(val),
10571048#if LLVM_VERSION_GE(18, 0)
1058 llvm::dwarf::DW_TAG_member,
1049 llvm::dwarf::DW_TAG_member,
10591050#endif
1060 AlignInBits
1061 ));
1051 AlignInBits));
10621052}
10631053
1064extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
1065 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1066 LLVMMetadataRef File, unsigned Line, unsigned Col) {
1054extern "C" LLVMMetadataRef
1055LLVMRustDIBuilderCreateLexicalBlock(LLVMRustDIBuilderRef Builder,
1056 LLVMMetadataRef Scope, LLVMMetadataRef File,
1057 unsigned Line, unsigned Col) {
10671058 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
10681059 unwrapDI<DIFile>(File), Line, Col));
10691060}
10701061
1071extern "C" LLVMMetadataRef
1072LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
1073 LLVMMetadataRef Scope,
1074 LLVMMetadataRef File) {
1062extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlockFile(
1063 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File) {
10751064 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
10761065 unwrapDI<DIFile>(File)));
10771066}
10781067
10791068extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
1080 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context,
1081 const char *Name, size_t NameLen,
1082 const char *LinkageName, size_t LinkageNameLen,
1083 LLVMMetadataRef File, unsigned LineNo,
1084 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
1085 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
1069 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
1070 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
1071 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1072 bool IsLocalToUnit, LLVMValueRef V, LLVMMetadataRef Decl = nullptr,
1073 uint32_t AlignInBits = 0) {
10861074 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
10871075
10881076 llvm::DIExpression *InitExpr = nullptr;
......@@ -1095,14 +1083,13 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
10951083 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
10961084 }
10971085
1098 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
1099 unwrapDI<DIDescriptor>(Context), StringRef(Name, NameLen),
1100 StringRef(LinkageName, LinkageNameLen),
1101 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
1102 /* isDefined */ true,
1103 InitExpr, unwrapDIPtr<MDNode>(Decl),
1104 /* templateParams */ nullptr,
1105 AlignInBits);
1086 llvm::DIGlobalVariableExpression *VarExpr =
1087 Builder->createGlobalVariableExpression(
1088 unwrapDI<DIDescriptor>(Context), StringRef(Name, NameLen),
1089 StringRef(LinkageName, LinkageNameLen), unwrapDI<DIFile>(File),
1090 LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
1091 /* isDefined */ true, InitExpr, unwrapDIPtr<MDNode>(Decl),
1092 /* templateParams */ nullptr, AlignInBits);
11061093
11071094 InitVal->setMetadata("dbg", VarExpr);
11081095
......@@ -1111,20 +1098,19 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
11111098
11121099extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
11131100 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
1114 const char *Name, size_t NameLen,
1115 LLVMMetadataRef File, unsigned LineNo,
1101 const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo,
11161102 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
11171103 unsigned ArgNo, uint32_t AlignInBits) {
11181104 if (Tag == 0x100) { // DW_TAG_auto_variable
11191105 return wrap(Builder->createAutoVariable(
11201106 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1121 unwrapDI<DIFile>(File), LineNo,
1122 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
1107 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve,
1108 fromRust(Flags), AlignInBits));
11231109 } else {
11241110 return wrap(Builder->createParameterVariable(
11251111 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen), ArgNo,
1126 unwrapDI<DIFile>(File), LineNo,
1127 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
1112 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve,
1113 fromRust(Flags)));
11281114 }
11291115}
11301116
......@@ -1157,9 +1143,9 @@ extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
11571143 LLVMBasicBlockRef InsertAtEnd) {
11581144 auto Result = Builder->insertDeclare(
11591145 unwrap(V), unwrap<DILocalVariable>(VarInfo),
1160 Builder->createExpression(llvm::ArrayRef<uint64_t>(AddrOps, AddrOpsCount)),
1161 DebugLoc(cast<MDNode>(unwrap(DL))),
1162 unwrap(InsertAtEnd));
1146 Builder->createExpression(
1147 llvm::ArrayRef<uint64_t>(AddrOps, AddrOpsCount)),
1148 DebugLoc(cast<MDNode>(unwrap(DL))), unwrap(InsertAtEnd));
11631149#if LLVM_VERSION_GE(19, 0)
11641150 return wrap(Result.get<llvm::Instruction *>());
11651151#else
......@@ -1170,21 +1156,20 @@ extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
11701156extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerator(
11711157 LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen,
11721158 const uint64_t Value[2], unsigned SizeInBits, bool IsUnsigned) {
1173 return wrap(Builder->createEnumerator(StringRef(Name, NameLen),
1159 return wrap(Builder->createEnumerator(
1160 StringRef(Name, NameLen),
11741161 APSInt(APInt(SizeInBits, ArrayRef<uint64_t>(Value, 2)), IsUnsigned)));
11751162}
11761163
11771164extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
1178 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1179 const char *Name, size_t NameLen,
1180 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1181 uint32_t AlignInBits, LLVMMetadataRef Elements,
1165 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1166 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1167 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef Elements,
11821168 LLVMMetadataRef ClassTy, bool IsScoped) {
11831169 return wrap(Builder->createEnumerationType(
11841170 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1185 unwrapDI<DIFile>(File), LineNumber,
1186 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
1187 unwrapDI<DIType>(ClassTy),
1171 unwrapDI<DIFile>(File), LineNumber, SizeInBits, AlignInBits,
1172 DINodeArray(unwrapDI<MDTuple>(Elements)), unwrapDI<DIType>(ClassTy),
11881173#if LLVM_VERSION_GE(18, 0)
11891174 /* RunTimeLang */ 0,
11901175#endif
......@@ -1192,39 +1177,38 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
11921177}
11931178
11941179extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
1195 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1196 const char *Name, size_t NameLen,
1197 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1198 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
1199 unsigned RunTimeLang, const char *UniqueId, size_t UniqueIdLen) {
1180 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1181 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1182 uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags,
1183 LLVMMetadataRef Elements, unsigned RunTimeLang, const char *UniqueId,
1184 size_t UniqueIdLen) {
12001185 return wrap(Builder->createUnionType(
1201 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen), unwrapDI<DIFile>(File),
1202 LineNumber, SizeInBits, AlignInBits, fromRust(Flags),
1203 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
1186 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1187 unwrapDI<DIFile>(File), LineNumber, SizeInBits, AlignInBits,
1188 fromRust(Flags), DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
12041189 StringRef(UniqueId, UniqueIdLen)));
12051190}
12061191
12071192extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
1208 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1209 const char *Name, size_t NameLen, LLVMMetadataRef Ty) {
1193 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1194 size_t NameLen, LLVMMetadataRef Ty) {
12101195 bool IsDefault = false; // FIXME: should we ever set this true?
12111196 return wrap(Builder->createTemplateTypeParameter(
1212 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen), unwrapDI<DIType>(Ty), IsDefault));
1197 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen),
1198 unwrapDI<DIType>(Ty), IsDefault));
12131199}
12141200
1215extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateNameSpace(
1216 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
1217 const char *Name, size_t NameLen, bool ExportSymbols) {
1201extern "C" LLVMMetadataRef
1202LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
1203 LLVMMetadataRef Scope, const char *Name,
1204 size_t NameLen, bool ExportSymbols) {
12181205 return wrap(Builder->createNameSpace(
1219 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen), ExportSymbols
1220 ));
1206 unwrapDI<DIDescriptor>(Scope), StringRef(Name, NameLen), ExportSymbols));
12211207}
12221208
1223extern "C" void
1224LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder,
1225 LLVMMetadataRef CompositeTy,
1226 LLVMMetadataRef Elements,
1227 LLVMMetadataRef Params) {
1209extern "C" void LLVMRustDICompositeTypeReplaceArrays(
1210 LLVMRustDIBuilderRef Builder, LLVMMetadataRef CompositeTy,
1211 LLVMMetadataRef Elements, LLVMMetadataRef Params) {
12281212 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
12291213 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(Elements)),
12301214 DINodeArray(unwrap<MDTuple>(Params)));
......@@ -1235,9 +1219,8 @@ LLVMRustDIBuilderCreateDebugLocation(unsigned Line, unsigned Column,
12351219 LLVMMetadataRef ScopeRef,
12361220 LLVMMetadataRef InlinedAt) {
12371221 MDNode *Scope = unwrapDIPtr<MDNode>(ScopeRef);
1238 DILocation *Loc = DILocation::get(
1239 Scope->getContext(), Line, Column, Scope,
1240 unwrapDIPtr<MDNode>(InlinedAt));
1222 DILocation *Loc = DILocation::get(Scope->getContext(), Line, Column, Scope,
1223 unwrapDIPtr<MDNode>(InlinedAt));
12411224 return wrap(Loc);
12421225}
12431226
......@@ -1258,8 +1241,7 @@ extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
12581241 unwrap<llvm::Type>(Ty)->print(OS);
12591242}
12601243
1261extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
1262 RustStringRef Str) {
1244extern "C" void LLVMRustWriteValueToString(LLVMValueRef V, RustStringRef Str) {
12631245 auto OS = RawRustStringOstream(Str);
12641246 if (!V) {
12651247 OS << "(null)";
......@@ -1281,7 +1263,7 @@ extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
12811263
12821264extern "C" void LLVMRustUnpackOptimizationDiagnostic(
12831265 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
1284 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
1266 LLVMValueRef *FunctionOut, unsigned *Line, unsigned *Column,
12851267 RustStringRef FilenameOut, RustStringRef MessageOut) {
12861268 // Undefined to call this not on an optimization diagnostic!
12871269 llvm::DiagnosticInfoOptimizationBase *Opt =
......@@ -1304,17 +1286,15 @@ extern "C" void LLVMRustUnpackOptimizationDiagnostic(
13041286}
13051287
13061288enum class LLVMRustDiagnosticLevel {
1307 Error,
1308 Warning,
1309 Note,
1310 Remark,
1289 Error,
1290 Warning,
1291 Note,
1292 Remark,
13111293};
13121294
1313extern "C" void
1314LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI,
1315 LLVMRustDiagnosticLevel *LevelOut,
1316 uint64_t *CookieOut,
1317 LLVMTwineRef *MessageOut) {
1295extern "C" void LLVMRustUnpackInlineAsmDiagnostic(
1296 LLVMDiagnosticInfoRef DI, LLVMRustDiagnosticLevel *LevelOut,
1297 uint64_t *CookieOut, LLVMTwineRef *MessageOut) {
13181298 // Undefined to call this not on an inline assembly diagnostic!
13191299 llvm::DiagnosticInfoInlineAsm *IA =
13201300 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
......@@ -1323,20 +1303,20 @@ LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI,
13231303 *MessageOut = wrap(&IA->getMsgStr());
13241304
13251305 switch (IA->getSeverity()) {
1326 case DS_Error:
1327 *LevelOut = LLVMRustDiagnosticLevel::Error;
1328 break;
1329 case DS_Warning:
1330 *LevelOut = LLVMRustDiagnosticLevel::Warning;
1331 break;
1332 case DS_Note:
1333 *LevelOut = LLVMRustDiagnosticLevel::Note;
1334 break;
1335 case DS_Remark:
1336 *LevelOut = LLVMRustDiagnosticLevel::Remark;
1337 break;
1338 default:
1339 report_fatal_error("Invalid LLVMRustDiagnosticLevel value!");
1306 case DS_Error:
1307 *LevelOut = LLVMRustDiagnosticLevel::Error;
1308 break;
1309 case DS_Warning:
1310 *LevelOut = LLVMRustDiagnosticLevel::Warning;
1311 break;
1312 case DS_Note:
1313 *LevelOut = LLVMRustDiagnosticLevel::Note;
1314 break;
1315 case DS_Remark:
1316 *LevelOut = LLVMRustDiagnosticLevel::Remark;
1317 break;
1318 default:
1319 report_fatal_error("Invalid LLVMRustDiagnosticLevel value!");
13401320 }
13411321}
13421322
......@@ -1454,61 +1434,61 @@ extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
14541434 return LLVMBFloatTypeKind;
14551435 case Type::X86_AMXTyID:
14561436 return LLVMX86_AMXTypeKind;
1457 default:
1458 {
1459 std::string error;
1460 auto stream = llvm::raw_string_ostream(error);
1461 stream << "Rust does not support the TypeID: " << unwrap(Ty)->getTypeID()
1462 << " for the type: " << *unwrap(Ty);
1463 stream.flush();
1464 report_fatal_error(error.c_str());
1465 }
1437 default: {
1438 std::string error;
1439 auto stream = llvm::raw_string_ostream(error);
1440 stream << "Rust does not support the TypeID: " << unwrap(Ty)->getTypeID()
1441 << " for the type: " << *unwrap(Ty);
1442 stream.flush();
1443 report_fatal_error(error.c_str());
1444 }
14661445 }
14671446}
14681447
14691448DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
14701449
1471extern "C" LLVMSMDiagnosticRef LLVMRustGetSMDiagnostic(
1472 LLVMDiagnosticInfoRef DI, unsigned *Cookie) {
1473 llvm::DiagnosticInfoSrcMgr *SM = static_cast<llvm::DiagnosticInfoSrcMgr *>(unwrap(DI));
1450extern "C" LLVMSMDiagnosticRef LLVMRustGetSMDiagnostic(LLVMDiagnosticInfoRef DI,
1451 unsigned *Cookie) {
1452 llvm::DiagnosticInfoSrcMgr *SM =
1453 static_cast<llvm::DiagnosticInfoSrcMgr *>(unwrap(DI));
14741454 *Cookie = SM->getLocCookie();
14751455 return wrap(&SM->getSMDiag());
14761456}
14771457
1478extern "C" bool LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef,
1479 RustStringRef MessageOut,
1480 RustStringRef BufferOut,
1481 LLVMRustDiagnosticLevel* LevelOut,
1482 unsigned* LocOut,
1483 unsigned* RangesOut,
1484 size_t* NumRanges) {
1485 SMDiagnostic& D = *unwrap(DRef);
1458extern "C" bool
1459LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef, RustStringRef MessageOut,
1460 RustStringRef BufferOut,
1461 LLVMRustDiagnosticLevel *LevelOut, unsigned *LocOut,
1462 unsigned *RangesOut, size_t *NumRanges) {
1463 SMDiagnostic &D = *unwrap(DRef);
14861464 auto MessageOS = RawRustStringOstream(MessageOut);
14871465 MessageOS << D.getMessage();
14881466
14891467 switch (D.getKind()) {
1490 case SourceMgr::DK_Error:
1491 *LevelOut = LLVMRustDiagnosticLevel::Error;
1492 break;
1493 case SourceMgr::DK_Warning:
1494 *LevelOut = LLVMRustDiagnosticLevel::Warning;
1495 break;
1496 case SourceMgr::DK_Note:
1497 *LevelOut = LLVMRustDiagnosticLevel::Note;
1498 break;
1499 case SourceMgr::DK_Remark:
1500 *LevelOut = LLVMRustDiagnosticLevel::Remark;
1501 break;
1502 default:
1503 report_fatal_error("Invalid LLVMRustDiagnosticLevel value!");
1468 case SourceMgr::DK_Error:
1469 *LevelOut = LLVMRustDiagnosticLevel::Error;
1470 break;
1471 case SourceMgr::DK_Warning:
1472 *LevelOut = LLVMRustDiagnosticLevel::Warning;
1473 break;
1474 case SourceMgr::DK_Note:
1475 *LevelOut = LLVMRustDiagnosticLevel::Note;
1476 break;
1477 case SourceMgr::DK_Remark:
1478 *LevelOut = LLVMRustDiagnosticLevel::Remark;
1479 break;
1480 default:
1481 report_fatal_error("Invalid LLVMRustDiagnosticLevel value!");
15041482 }
15051483
15061484 if (D.getLoc() == SMLoc())
15071485 return false;
15081486
15091487 const SourceMgr &LSM = *D.getSourceMgr();
1510 const MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1511 LLVMRustStringWriteImpl(BufferOut, LBuf->getBufferStart(), LBuf->getBufferSize());
1488 const MemoryBuffer *LBuf =
1489 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1490 LLVMRustStringWriteImpl(BufferOut, LBuf->getBufferStart(),
1491 LBuf->getBufferSize());
15121492
15131493 *LocOut = D.getLoc().getPointer() - LBuf->getBufferStart();
15141494
......@@ -1525,7 +1505,8 @@ extern "C" bool LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef,
15251505extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
15261506 LLVMValueRef *Inputs,
15271507 unsigned NumInputs) {
1528 return new OperandBundleDef(Name, ArrayRef<Value*>(unwrap(Inputs), NumInputs));
1508 return new OperandBundleDef(Name,
1509 ArrayRef<Value *>(unwrap(Inputs), NumInputs));
15291510}
15301511
15311512extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
......@@ -1533,8 +1514,9 @@ extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
15331514}
15341515
15351516// OpBundlesIndirect is an array of pointers (*not* a pointer to an array).
1536extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
1537 LLVMValueRef *Args, unsigned NumArgs,
1517extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty,
1518 LLVMValueRef Fn, LLVMValueRef *Args,
1519 unsigned NumArgs,
15381520 OperandBundleDef **OpBundlesIndirect,
15391521 unsigned NumOpBundles) {
15401522 Value *Callee = unwrap(Fn);
......@@ -1547,17 +1529,19 @@ extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, LLVM
15471529 OpBundles.push_back(*OpBundlesIndirect[i]);
15481530 }
15491531
1550 return wrap(unwrap(B)->CreateCall(
1551 FTy, Callee, ArrayRef<Value*>(unwrap(Args), NumArgs),
1552 ArrayRef<OperandBundleDef>(OpBundles)));
1532 return wrap(unwrap(B)->CreateCall(FTy, Callee,
1533 ArrayRef<Value *>(unwrap(Args), NumArgs),
1534 ArrayRef<OperandBundleDef>(OpBundles)));
15531535}
15541536
1555extern "C" LLVMValueRef LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) {
1537extern "C" LLVMValueRef
1538LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) {
15561539 return wrap(llvm::Intrinsic::getDeclaration(
15571540 unwrap(M), llvm::Intrinsic::instrprof_increment));
15581541}
15591542
1560extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) {
1543extern "C" LLVMValueRef
1544LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) {
15611545#if LLVM_VERSION_GE(18, 0)
15621546 return wrap(llvm::Intrinsic::getDeclaration(
15631547 unwrap(M), llvm::Intrinsic::instrprof_mcdc_parameters));
......@@ -1566,7 +1550,8 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRe
15661550#endif
15671551}
15681552
1569extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) {
1553extern "C" LLVMValueRef
1554LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) {
15701555#if LLVM_VERSION_GE(18, 0)
15711556 return wrap(llvm::Intrinsic::getDeclaration(
15721557 unwrap(M), llvm::Intrinsic::instrprof_mcdc_tvbitmap_update));
......@@ -1575,7 +1560,8 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModu
15751560#endif
15761561}
15771562
1578extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRef M) {
1563extern "C" LLVMValueRef
1564LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRef M) {
15791565#if LLVM_VERSION_GE(18, 0)
15801566 return wrap(llvm::Intrinsic::getDeclaration(
15811567 unwrap(M), llvm::Intrinsic::instrprof_mcdc_condbitmap_update));
......@@ -1584,32 +1570,31 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRe
15841570#endif
15851571}
15861572
1587extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B,
1588 LLVMValueRef Dst, unsigned DstAlign,
1589 LLVMValueRef Src, unsigned SrcAlign,
1590 LLVMValueRef Size, bool IsVolatile) {
1591 return wrap(unwrap(B)->CreateMemCpy(
1592 unwrap(Dst), MaybeAlign(DstAlign),
1593 unwrap(Src), MaybeAlign(SrcAlign),
1594 unwrap(Size), IsVolatile));
1573extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, LLVMValueRef Dst,
1574 unsigned DstAlign, LLVMValueRef Src,
1575 unsigned SrcAlign,
1576 LLVMValueRef Size,
1577 bool IsVolatile) {
1578 return wrap(unwrap(B)->CreateMemCpy(unwrap(Dst), MaybeAlign(DstAlign),
1579 unwrap(Src), MaybeAlign(SrcAlign),
1580 unwrap(Size), IsVolatile));
15951581}
15961582
1597extern "C" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B,
1598 LLVMValueRef Dst, unsigned DstAlign,
1599 LLVMValueRef Src, unsigned SrcAlign,
1600 LLVMValueRef Size, bool IsVolatile) {
1601 return wrap(unwrap(B)->CreateMemMove(
1602 unwrap(Dst), MaybeAlign(DstAlign),
1603 unwrap(Src), MaybeAlign(SrcAlign),
1604 unwrap(Size), IsVolatile));
1583extern "C" LLVMValueRef
1584LLVMRustBuildMemMove(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign,
1585 LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size,
1586 bool IsVolatile) {
1587 return wrap(unwrap(B)->CreateMemMove(unwrap(Dst), MaybeAlign(DstAlign),
1588 unwrap(Src), MaybeAlign(SrcAlign),
1589 unwrap(Size), IsVolatile));
16051590}
16061591
1607extern "C" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B,
1608 LLVMValueRef Dst, unsigned DstAlign,
1609 LLVMValueRef Val,
1610 LLVMValueRef Size, bool IsVolatile) {
1611 return wrap(unwrap(B)->CreateMemSet(
1612 unwrap(Dst), unwrap(Val), unwrap(Size), MaybeAlign(DstAlign), IsVolatile));
1592extern "C" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B, LLVMValueRef Dst,
1593 unsigned DstAlign, LLVMValueRef Val,
1594 LLVMValueRef Size,
1595 bool IsVolatile) {
1596 return wrap(unwrap(B)->CreateMemSet(unwrap(Dst), unwrap(Val), unwrap(Size),
1597 MaybeAlign(DstAlign), IsVolatile));
16131598}
16141599
16151600// OpBundlesIndirect is an array of pointers (*not* a pointer to an array).
......@@ -1630,7 +1615,7 @@ LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
16301615 }
16311616
16321617 return wrap(unwrap(B)->CreateInvoke(FTy, Callee, unwrap(Then), unwrap(Catch),
1633 ArrayRef<Value*>(unwrap(Args), NumArgs),
1618 ArrayRef<Value *>(unwrap(Args), NumArgs),
16341619 ArrayRef<OperandBundleDef>(OpBundles),
16351620 Name));
16361621}
......@@ -1647,7 +1632,7 @@ LLVMRustBuildCallBr(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
16471632 FunctionType *FTy = unwrap<FunctionType>(Ty);
16481633
16491634 // FIXME: Is there a way around this?
1650 std::vector<BasicBlock*> IndirectDestsUnwrapped;
1635 std::vector<BasicBlock *> IndirectDestsUnwrapped;
16511636 IndirectDestsUnwrapped.reserve(NumIndirectDests);
16521637 for (unsigned i = 0; i < NumIndirectDests; ++i) {
16531638 IndirectDestsUnwrapped.push_back(unwrap(IndirectDests[i]));
......@@ -1660,12 +1645,11 @@ LLVMRustBuildCallBr(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn,
16601645 OpBundles.push_back(*OpBundlesIndirect[i]);
16611646 }
16621647
1663 return wrap(unwrap(B)->CreateCallBr(
1664 FTy, Callee, unwrap(DefaultDest),
1665 ArrayRef<BasicBlock*>(IndirectDestsUnwrapped),
1666 ArrayRef<Value*>(unwrap(Args), NumArgs),
1667 ArrayRef<OperandBundleDef>(OpBundles),
1668 Name));
1648 return wrap(
1649 unwrap(B)->CreateCallBr(FTy, Callee, unwrap(DefaultDest),
1650 ArrayRef<BasicBlock *>(IndirectDestsUnwrapped),
1651 ArrayRef<Value *>(unwrap(Args), NumArgs),
1652 ArrayRef<OperandBundleDef>(OpBundles), Name));
16691653}
16701654
16711655extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
......@@ -1765,28 +1749,30 @@ extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
17651749}
17661750
17671751extern "C" bool LLVMRustConstIntGetZExtValue(LLVMValueRef CV, uint64_t *value) {
1768 auto C = unwrap<llvm::ConstantInt>(CV);
1769 if (C->getBitWidth() > 64)
1770 return false;
1771 *value = C->getZExtValue();
1772 return true;
1752 auto C = unwrap<llvm::ConstantInt>(CV);
1753 if (C->getBitWidth() > 64)
1754 return false;
1755 *value = C->getZExtValue();
1756 return true;
17731757}
17741758
1775// Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1776// the common sizes (1, 8, 16, 32, 64, 128 bits)
1777extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1778{
1779 auto C = unwrap<llvm::ConstantInt>(CV);
1780 if (C->getBitWidth() > 128) { return false; }
1781 APInt AP;
1782 if (sext) {
1783 AP = C->getValue().sext(128);
1784 } else {
1785 AP = C->getValue().zext(128);
1786 }
1787 *low = AP.getLoBits(64).getZExtValue();
1788 *high = AP.getHiBits(64).getZExtValue();
1789 return true;
1759// Returns true if both high and low were successfully set. Fails in case
1760// constant wasn’t any of the common sizes (1, 8, 16, 32, 64, 128 bits)
1761extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext,
1762 uint64_t *high, uint64_t *low) {
1763 auto C = unwrap<llvm::ConstantInt>(CV);
1764 if (C->getBitWidth() > 128) {
1765 return false;
1766 }
1767 APInt AP;
1768 if (sext) {
1769 AP = C->getValue().sext(128);
1770 } else {
1771 AP = C->getValue().zext(128);
1772 }
1773 *low = AP.getLoBits(64).getZExtValue();
1774 *high = AP.getHiBits(64).getZExtValue();
1775 return true;
17901776}
17911777
17921778enum class LLVMRustVisibility {
......@@ -1836,8 +1822,7 @@ struct LLVMRustModuleBuffer {
18361822 std::string data;
18371823};
18381824
1839extern "C" LLVMRustModuleBuffer*
1840LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1825extern "C" LLVMRustModuleBuffer *LLVMRustModuleBufferCreate(LLVMModuleRef M) {
18411826 auto Ret = std::make_unique<LLVMRustModuleBuffer>();
18421827 {
18431828 auto OS = raw_string_ostream(Ret->data);
......@@ -1846,30 +1831,26 @@ LLVMRustModuleBufferCreate(LLVMModuleRef M) {
18461831 return Ret.release();
18471832}
18481833
1849extern "C" void
1850LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1834extern "C" void LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
18511835 delete Buffer;
18521836}
18531837
1854extern "C" const void*
1838extern "C" const void *
18551839LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
18561840 return Buffer->data.data();
18571841}
18581842
1859extern "C" size_t
1860LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1843extern "C" size_t LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
18611844 return Buffer->data.length();
18621845}
18631846
1864extern "C" uint64_t
1865LLVMRustModuleCost(LLVMModuleRef M) {
1847extern "C" uint64_t LLVMRustModuleCost(LLVMModuleRef M) {
18661848 auto f = unwrap(M)->functions();
18671849 return std::distance(std::begin(f), std::end(f));
18681850}
18691851
1870extern "C" void
1871LLVMRustModuleInstructionStats(LLVMModuleRef M, RustStringRef Str)
1872{
1852extern "C" void LLVMRustModuleInstructionStats(LLVMModuleRef M,
1853 RustStringRef Str) {
18731854 auto OS = RawRustStringOstream(Str);
18741855 auto JOS = llvm::json::OStream(OS);
18751856 auto Module = unwrap(M);
......@@ -1881,41 +1862,45 @@ LLVMRustModuleInstructionStats(LLVMModuleRef M, RustStringRef Str)
18811862}
18821863
18831864// Vector reductions:
1884extern "C" LLVMValueRef
1885LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1886 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1887}
1888extern "C" LLVMValueRef
1889LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1890 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1891}
1892extern "C" LLVMValueRef
1893LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1894 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1895}
1896extern "C" LLVMValueRef
1897LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1898 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1899}
1900extern "C" LLVMValueRef
1901LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1902 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1903}
1904extern "C" LLVMValueRef
1905LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1906 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1907}
1908extern "C" LLVMValueRef
1909LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1910 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1911}
1912extern "C" LLVMValueRef
1913LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1914 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1915}
1916extern "C" LLVMValueRef
1917LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1918 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1865extern "C" LLVMValueRef LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B,
1866 LLVMValueRef Acc,
1867 LLVMValueRef Src) {
1868 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc), unwrap(Src)));
1869}
1870extern "C" LLVMValueRef LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B,
1871 LLVMValueRef Acc,
1872 LLVMValueRef Src) {
1873 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc), unwrap(Src)));
1874}
1875extern "C" LLVMValueRef LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B,
1876 LLVMValueRef Src) {
1877 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1878}
1879extern "C" LLVMValueRef LLVMRustBuildVectorReduceMul(LLVMBuilderRef B,
1880 LLVMValueRef Src) {
1881 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1882}
1883extern "C" LLVMValueRef LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B,
1884 LLVMValueRef Src) {
1885 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1886}
1887extern "C" LLVMValueRef LLVMRustBuildVectorReduceOr(LLVMBuilderRef B,
1888 LLVMValueRef Src) {
1889 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1890}
1891extern "C" LLVMValueRef LLVMRustBuildVectorReduceXor(LLVMBuilderRef B,
1892 LLVMValueRef Src) {
1893 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1894}
1895extern "C" LLVMValueRef LLVMRustBuildVectorReduceMin(LLVMBuilderRef B,
1896 LLVMValueRef Src,
1897 bool IsSigned) {
1898 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1899}
1900extern "C" LLVMValueRef LLVMRustBuildVectorReduceMax(LLVMBuilderRef B,
1901 LLVMValueRef Src,
1902 bool IsSigned) {
1903 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
19191904}
19201905extern "C" LLVMValueRef
19211906LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
......@@ -1930,32 +1915,28 @@ LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
19301915 return wrap(I);
19311916}
19321917
1933extern "C" LLVMValueRef
1934LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1935 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1918extern "C" LLVMValueRef LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS,
1919 LLVMValueRef RHS) {
1920 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS), unwrap(RHS)));
19361921}
1937extern "C" LLVMValueRef
1938LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1939 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1922extern "C" LLVMValueRef LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS,
1923 LLVMValueRef RHS) {
1924 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS), unwrap(RHS)));
19401925}
19411926
19421927// This struct contains all necessary info about a symbol exported from a DLL.
19431928struct LLVMRustCOFFShortExport {
1944 const char* name;
1929 const char *name;
19451930 bool ordinal_present;
19461931 // The value of `ordinal` is only meaningful if `ordinal_present` is true.
19471932 uint16_t ordinal;
19481933};
19491934
19501935// Machine must be a COFF machine type, as defined in PE specs.
1951extern "C" LLVMRustResult LLVMRustWriteImportLibrary(
1952 const char* ImportName,
1953 const char* Path,
1954 const LLVMRustCOFFShortExport* Exports,
1955 size_t NumExports,
1956 uint16_t Machine,
1957 bool MinGW)
1958{
1936extern "C" LLVMRustResult
1937LLVMRustWriteImportLibrary(const char *ImportName, const char *Path,
1938 const LLVMRustCOFFShortExport *Exports,
1939 size_t NumExports, uint16_t Machine, bool MinGW) {
19591940 std::vector<llvm::object::COFFShortExport> ConvertedExports;
19601941 ConvertedExports.reserve(NumExports);
19611942
......@@ -1963,27 +1944,24 @@ extern "C" LLVMRustResult LLVMRustWriteImportLibrary(
19631944 bool ordinal_present = Exports[i].ordinal_present;
19641945 uint16_t ordinal = ordinal_present ? Exports[i].ordinal : 0;
19651946 ConvertedExports.push_back(llvm::object::COFFShortExport{
1966 Exports[i].name, // Name
1967 std::string{}, // ExtName
1968 std::string{}, // SymbolName
1969 std::string{}, // AliasTarget
1947 Exports[i].name, // Name
1948 std::string{}, // ExtName
1949 std::string{}, // SymbolName
1950 std::string{}, // AliasTarget
19701951#if LLVM_VERSION_GE(19, 0)
1971 std::string{}, // ExportAs
1952 std::string{}, // ExportAs
19721953#endif
1973 ordinal, // Ordinal
1974 ordinal_present, // Noname
1975 false, // Data
1976 false, // Private
1977 false // Constant
1954 ordinal, // Ordinal
1955 ordinal_present, // Noname
1956 false, // Data
1957 false, // Private
1958 false // Constant
19781959 });
19791960 }
19801961
19811962 auto Error = llvm::object::writeImportLibrary(
1982 ImportName,
1983 Path,
1984 ConvertedExports,
1985 static_cast<llvm::COFF::MachineTypes>(Machine),
1986 MinGW);
1963 ImportName, Path, ConvertedExports,
1964 static_cast<llvm::COFF::MachineTypes>(Machine), MinGW);
19871965 if (Error) {
19881966 std::string errorString;
19891967 auto stream = llvm::raw_string_ostream(errorString);
......@@ -2019,27 +1997,23 @@ using LLVMDiagnosticHandlerTy = DiagnosticHandler::DiagnosticHandlerTy;
20191997// the RemarkPasses array specifies individual passes for which remarks will be
20201998// enabled.
20211999//
2022// If RemarkFilePath is not NULL, optimization remarks will be streamed directly into this file,
2023// bypassing the diagnostics handler.
2000// If RemarkFilePath is not NULL, optimization remarks will be streamed directly
2001// into this file, bypassing the diagnostics handler.
20242002extern "C" void LLVMRustContextConfigureDiagnosticHandler(
20252003 LLVMContextRef C, LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
20262004 void *DiagnosticHandlerContext, bool RemarkAllPasses,
2027 const char * const * RemarkPasses, size_t RemarkPassesLen,
2028 const char * RemarkFilePath,
2029 bool PGOAvailable
2030) {
2005 const char *const *RemarkPasses, size_t RemarkPassesLen,
2006 const char *RemarkFilePath, bool PGOAvailable) {
20312007
20322008 class RustDiagnosticHandler final : public DiagnosticHandler {
20332009 public:
20342010 RustDiagnosticHandler(
2035 LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
2036 void *DiagnosticHandlerContext,
2037 bool RemarkAllPasses,
2038 std::vector<std::string> RemarkPasses,
2039 std::unique_ptr<ToolOutputFile> RemarksFile,
2040 std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer,
2041 std::unique_ptr<LLVMRemarkStreamer> LlvmRemarkStreamer
2042 )
2011 LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
2012 void *DiagnosticHandlerContext, bool RemarkAllPasses,
2013 std::vector<std::string> RemarkPasses,
2014 std::unique_ptr<ToolOutputFile> RemarksFile,
2015 std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer,
2016 std::unique_ptr<LLVMRemarkStreamer> LlvmRemarkStreamer)
20432017 : DiagnosticHandlerCallback(DiagnosticHandlerCallback),
20442018 DiagnosticHandlerContext(DiagnosticHandlerContext),
20452019 RemarkAllPasses(RemarkAllPasses),
......@@ -2049,11 +2023,13 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler(
20492023 LlvmRemarkStreamer(std::move(LlvmRemarkStreamer)) {}
20502024
20512025 virtual bool handleDiagnostics(const DiagnosticInfo &DI) override {
2052 // If this diagnostic is one of the optimization remark kinds, we can check if it's enabled
2053 // before emitting it. This can avoid many short-lived allocations when unpacking the
2054 // diagnostic and converting its various C++ strings into rust strings.
2055 // FIXME: some diagnostic infos still allocate before we get here, and avoiding that would be
2056 // good in the future. That will require changing a few call sites in LLVM.
2026 // If this diagnostic is one of the optimization remark kinds, we can
2027 // check if it's enabled before emitting it. This can avoid many
2028 // short-lived allocations when unpacking the diagnostic and converting
2029 // its various C++ strings into rust strings.
2030 // FIXME: some diagnostic infos still allocate before we get here, and
2031 // avoiding that would be good in the future. That will require changing a
2032 // few call sites in LLVM.
20572033 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) {
20582034 if (OptDiagBase->isEnabled()) {
20592035 if (this->LlvmRemarkStreamer) {
......@@ -2109,16 +2085,15 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler(
21092085 bool RemarkAllPasses = false;
21102086 std::vector<std::string> RemarkPasses;
21112087
2112 // Since LlvmRemarkStreamer contains a pointer to RemarkStreamer, the ordering of the three
2113 // members below is important.
2088 // Since LlvmRemarkStreamer contains a pointer to RemarkStreamer, the
2089 // ordering of the three members below is important.
21142090 std::unique_ptr<ToolOutputFile> RemarksFile;
21152091 std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer;
21162092 std::unique_ptr<LLVMRemarkStreamer> LlvmRemarkStreamer;
21172093 };
21182094
21192095 std::vector<std::string> Passes;
2120 for (size_t I = 0; I != RemarkPassesLen; ++I)
2121 {
2096 for (size_t I = 0; I != RemarkPassesLen; ++I) {
21222097 Passes.push_back(RemarkPasses[I]);
21232098 }
21242099
......@@ -2135,13 +2110,10 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler(
21352110
21362111 std::error_code EC;
21372112 RemarkFile = std::make_unique<ToolOutputFile>(
2138 RemarkFilePath,
2139 EC,
2140 llvm::sys::fs::OF_TextWithCRLF
2141 );
2113 RemarkFilePath, EC, llvm::sys::fs::OF_TextWithCRLF);
21422114 if (EC) {
21432115 std::string Error = std::string("Cannot create remark file: ") +
2144 toString(errorCodeToError(EC));
2116 toString(errorCodeToError(EC));
21452117 report_fatal_error(Twine(Error));
21462118 }
21472119
......@@ -2149,28 +2121,22 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler(
21492121 RemarkFile->keep();
21502122
21512123 auto RemarkSerializer = remarks::createRemarkSerializer(
2152 llvm::remarks::Format::YAML,
2153 remarks::SerializerMode::Separate,
2154 RemarkFile->os()
2155 );
2156 if (Error E = RemarkSerializer.takeError())
2157 {
2158 std::string Error = std::string("Cannot create remark serializer: ") + toString(std::move(E));
2124 llvm::remarks::Format::YAML, remarks::SerializerMode::Separate,
2125 RemarkFile->os());
2126 if (Error E = RemarkSerializer.takeError()) {
2127 std::string Error = std::string("Cannot create remark serializer: ") +
2128 toString(std::move(E));
21592129 report_fatal_error(Twine(Error));
21602130 }
2161 RemarkStreamer = std::make_unique<llvm::remarks::RemarkStreamer>(std::move(*RemarkSerializer));
2131 RemarkStreamer = std::make_unique<llvm::remarks::RemarkStreamer>(
2132 std::move(*RemarkSerializer));
21622133 LlvmRemarkStreamer = std::make_unique<LLVMRemarkStreamer>(*RemarkStreamer);
21632134 }
21642135
21652136 unwrap(C)->setDiagnosticHandler(std::make_unique<RustDiagnosticHandler>(
2166 DiagnosticHandlerCallback,
2167 DiagnosticHandlerContext,
2168 RemarkAllPasses,
2169 Passes,
2170 std::move(RemarkFile),
2171 std::move(RemarkStreamer),
2172 std::move(LlvmRemarkStreamer)
2173 ));
2137 DiagnosticHandlerCallback, DiagnosticHandlerContext, RemarkAllPasses,
2138 Passes, std::move(RemarkFile), std::move(RemarkStreamer),
2139 std::move(LlvmRemarkStreamer)));
21742140}
21752141
21762142extern "C" void LLVMRustGetMangledName(LLVMValueRef V, RustStringRef Str) {
......@@ -2180,14 +2146,14 @@ extern "C" void LLVMRustGetMangledName(LLVMValueRef V, RustStringRef Str) {
21802146}
21812147
21822148extern "C" int32_t LLVMRustGetElementTypeArgIndex(LLVMValueRef CallSite) {
2183 auto *CB = unwrap<CallBase>(CallSite);
2184 switch (CB->getIntrinsicID()) {
2185 case Intrinsic::arm_ldrex:
2186 return 0;
2187 case Intrinsic::arm_strex:
2188 return 1;
2189 }
2190 return -1;
2149 auto *CB = unwrap<CallBase>(CallSite);
2150 switch (CB->getIntrinsicID()) {
2151 case Intrinsic::arm_ldrex:
2152 return 0;
2153 case Intrinsic::arm_strex:
2154 return 1;
2155 }
2156 return -1;
21912157}
21922158
21932159extern "C" bool LLVMRustIsBitcode(char *ptr, size_t len) {
......@@ -2214,10 +2180,10 @@ extern "C" bool LLVMRustLLVMHasZstdCompressionForDebugSymbols() {
22142180}
22152181
22162182// Operations on composite constants.
2217// These are clones of LLVM api functions that will become available in future releases.
2218// They can be removed once Rust's minimum supported LLVM version supports them.
2219// See https://github.com/rust-lang/rust/issues/121868
2220// See https://llvm.org/doxygen/group__LLVMCCoreValueConstantComposite.html
2183// These are clones of LLVM api functions that will become available in future
2184// releases. They can be removed once Rust's minimum supported LLVM version
2185// supports them. See https://github.com/rust-lang/rust/issues/121868 See
2186// https://llvm.org/doxygen/group__LLVMCCoreValueConstantComposite.html
22212187
22222188// FIXME: Remove when Rust's minimum supported LLVM version reaches 19.
22232189// https://github.com/llvm/llvm-project/commit/e1405e4f71c899420ebf8262d5e9745598419df8
......@@ -2226,6 +2192,7 @@ extern "C" LLVMValueRef LLVMConstStringInContext2(LLVMContextRef C,
22262192 const char *Str,
22272193 size_t Length,
22282194 bool DontNullTerminate) {
2229 return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length), !DontNullTerminate));
2195 return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length),
2196 !DontNullTerminate));
22302197}
22312198#endif
compiler/rustc_llvm/llvm-wrapper/SuppressLLVMWarnings.h+9-5
......@@ -1,13 +1,17 @@
11#ifndef _rustc_llvm_SuppressLLVMWarnings_h
22#define _rustc_llvm_SuppressLLVMWarnings_h
33
4// LLVM currently generates many warnings when compiled using MSVC. These warnings make it difficult
5// to diagnose real problems when working on C++ code, so we suppress them.
4// LLVM currently generates many warnings when compiled using MSVC. These
5// warnings make it difficult to diagnose real problems when working on C++
6// code, so we suppress them.
67
78#ifdef _MSC_VER
8#pragma warning(disable:4530) // C++ exception handler used, but unwind semantics are not enabled.
9#pragma warning(disable:4624) // 'xxx': destructor was implicitly defined as deleted
10#pragma warning(disable:4244) // conversion from 'xxx' to 'yyy', possible loss of data
9#pragma warning(disable : 4530) // C++ exception handler used, but unwind
10 // semantics are not enabled.
11#pragma warning( \
12 disable : 4624) // 'xxx': destructor was implicitly defined as deleted
13#pragma warning( \
14 disable : 4244) // conversion from 'xxx' to 'yyy', possible loss of data
1115#endif
1216
1317#endif // _rustc_llvm_SuppressLLVMWarnings_h
compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp+12-11
......@@ -34,14 +34,15 @@ static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
3434typedef void *(*LLVMRustGetSymbolsCallback)(void *, const char *);
3535typedef void *(*LLVMRustGetSymbolsErrorCallback)(const char *);
3636
37// Note: This is implemented in C++ instead of using the C api from Rust as IRObjectFile doesn't
38// implement getSymbolName, only printSymbolName, which is inaccessible from the C api.
39extern "C" void *LLVMRustGetSymbols(
40 char *BufPtr, size_t BufLen, void *State, LLVMRustGetSymbolsCallback Callback,
41 LLVMRustGetSymbolsErrorCallback ErrorCallback) {
42 std::unique_ptr<MemoryBuffer> Buf =
43 MemoryBuffer::getMemBuffer(StringRef(BufPtr, BufLen), StringRef("LLVMRustGetSymbolsObject"),
44 false);
37// Note: This is implemented in C++ instead of using the C api from Rust as
38// IRObjectFile doesn't implement getSymbolName, only printSymbolName, which is
39// inaccessible from the C api.
40extern "C" void *
41LLVMRustGetSymbols(char *BufPtr, size_t BufLen, void *State,
42 LLVMRustGetSymbolsCallback Callback,
43 LLVMRustGetSymbolsErrorCallback ErrorCallback) {
44 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(
45 StringRef(BufPtr, BufLen), StringRef("LLVMRustGetSymbolsObject"), false);
4546 SmallString<0> SymNameBuf;
4647 auto SymName = raw_svector_ostream(SymNameBuf);
4748
......@@ -57,7 +58,7 @@ extern "C" void *LLVMRustGetSymbols(
5758
5859 if (Type == file_magic::bitcode) {
5960 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
60 Buf->getMemBufferRef(), file_magic::bitcode, &Context);
61 Buf->getMemBufferRef(), file_magic::bitcode, &Context);
6162 if (!ObjOrErr) {
6263 Error E = ObjOrErr.takeError();
6364 SmallString<0> ErrorBuf;
......@@ -67,7 +68,8 @@ extern "C" void *LLVMRustGetSymbols(
6768 }
6869 Obj = std::move(*ObjOrErr);
6970 } else {
70 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf->getMemBufferRef());
71 auto ObjOrErr =
72 object::SymbolicFile::createSymbolicFile(Buf->getMemBufferRef());
7173 if (!ObjOrErr) {
7274 Error E = ObjOrErr.takeError();
7375 SmallString<0> ErrorBuf;
......@@ -78,7 +80,6 @@ extern "C" void *LLVMRustGetSymbols(
7880 Obj = std::move(*ObjOrErr);
7981 }
8082
81
8283 for (const object::BasicSymbolRef &S : Obj->symbols()) {
8384 if (!isArchiveSymbol(S))
8485 continue;
src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile+1-1
......@@ -35,4 +35,4 @@ COPY host-x86_64/mingw-check/validate-error-codes.sh /scripts/
3535# NOTE: intentionally uses python2 for x.py so we can test it still works.
3636# validate-toolstate only runs in our CI, so it's ok for it to only support python3.
3737ENV SCRIPT TIDY_PRINT_DIFF=1 python2.7 ../x.py test \
38 --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint
38 --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint,cpp:fmt
src/tools/tidy/Cargo.toml+1
......@@ -15,6 +15,7 @@ semver = "1.0"
1515termcolor = "1.1.3"
1616rustc-hash = "1.1.0"
1717fluent-syntax = "0.11.1"
18similar = "2.5.0"
1819
1920[[bin]]
2021name = "rust-tidy"
src/tools/tidy/config/requirements.in+1
......@@ -8,3 +8,4 @@
88
99black==24.4.2
1010ruff==0.4.9
11clang-format==18.1.7
src/tools/tidy/config/requirements.txt+17
......@@ -28,6 +28,23 @@ black==24.4.2 \
2828 --hash=sha256:eaea3008c281f1038edb473c1aa8ed8143a5535ff18f978a318f10302b254063 \
2929 --hash=sha256:ef703f83fc32e131e9bcc0a5094cfe85599e7109f896fe8bc96cc402f3eb4b6e
3030 # via -r src/tools/tidy/config/requirements.in
31clang-format==18.1.7 \
32 --hash=sha256:035204410f65d03f98cb81c9c39d6d193f9987917cc88de9d0dbd01f2aa9c302 \
33 --hash=sha256:05c482a854287a5d21f7567186c0bd4b8dbd4a871751e655a45849185f30b931 \
34 --hash=sha256:0b352ec51b291fe04c25a0f0ed15ba1a55b9c9c8eaa7fdf14de3d3585aef4f72 \
35 --hash=sha256:217526c8189c18fd175e19bb3e4da2d1bdf14a2bf79d97108c9b6a98d9938351 \
36 --hash=sha256:42d0b580ab7a45348155944adebe0bef53d1de9357b925830a59bbc351a25560 \
37 --hash=sha256:57090c40a8f0a898e0db8be150a19be2551302d5f5620d2a01de07e7c9220a53 \
38 --hash=sha256:607772cf474c1ebe0de44f44c1324e57a2d5b45a1d96d4aff166645532d99b43 \
39 --hash=sha256:a49c44d7cc00431be8285aa120a7a21fa0475786c03c53b04a26882c4e626a43 \
40 --hash=sha256:a62fca204293893badde0ab004df8b6df1d13eac4d452051554d9684d0a8254e \
41 --hash=sha256:a914592a51f77c3563563c7a8970f19bc1ed59174ab992f095a78f4e142382ac \
42 --hash=sha256:b3a0a09428cdd656ed87074543222a80660bc506407ed21b8e4bcb3d6d3a5a3c \
43 --hash=sha256:c151d42e6ac7c3cc03d7fec61bed3211ce8f75528e1efd8fc64bdb33840987b2 \
44 --hash=sha256:d6a2f051124d6ae506ba2a68accfe4ea4c8cb90d13b422c3131bb124413bac32 \
45 --hash=sha256:f4f77ac0f4f9a659213fedda0f2d216886c410132e6e7dd4b13f92b34e925554 \
46 --hash=sha256:f935d34152a2e11e55120eb9182862f432bc9789ab819f680c9f6db4edebf9e3
47 # via -r src/tools/tidy/config/requirements.in
3148click==8.1.3 \
3249 --hash=sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e \
3350 --hash=sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48
src/tools/tidy/src/ext_tool_checks.rs+122-12
......@@ -73,6 +73,8 @@ fn check_impl(
7373 let python_fmt = lint_args.contains(&"py:fmt") || python_all;
7474 let shell_all = lint_args.contains(&"shell");
7575 let shell_lint = lint_args.contains(&"shell:lint") || shell_all;
76 let cpp_all = lint_args.contains(&"cpp");
77 let cpp_fmt = lint_args.contains(&"cpp:fmt") || cpp_all;
7678
7779 let mut py_path = None;
7880
......@@ -81,7 +83,7 @@ fn check_impl(
8183 .map(OsStr::new)
8284 .partition(|arg| arg.to_str().is_some_and(|s| s.starts_with('-')));
8385
84 if python_lint || python_fmt {
86 if python_lint || python_fmt || cpp_fmt {
8587 let venv_path = outdir.join("venv");
8688 let mut reqs_path = root_path.to_owned();
8789 reqs_path.extend(PIP_REQ_PATH);
......@@ -111,13 +113,13 @@ fn check_impl(
111113
112114 let mut args = merge_args(&cfg_args_ruff, &file_args_ruff);
113115 args.insert(0, "check".as_ref());
114 let res = py_runner(py_path.as_ref().unwrap(), "ruff", &args);
116 let res = py_runner(py_path.as_ref().unwrap(), true, None, "ruff", &args);
115117
116118 if res.is_err() && show_diff {
117119 eprintln!("\npython linting failed! Printing diff suggestions:");
118120
119121 args.insert(1, "--diff".as_ref());
120 let _ = py_runner(py_path.as_ref().unwrap(), "ruff", &args);
122 let _ = py_runner(py_path.as_ref().unwrap(), true, None, "ruff", &args);
121123 }
122124 // Rethrow error
123125 let _ = res?;
......@@ -144,13 +146,84 @@ fn check_impl(
144146 }
145147
146148 let mut args = merge_args(&cfg_args_black, &file_args_black);
147 let res = py_runner(py_path.as_ref().unwrap(), "black", &args);
149 let res = py_runner(py_path.as_ref().unwrap(), true, None, "black", &args);
148150
149151 if res.is_err() && show_diff {
150152 eprintln!("\npython formatting does not match! Printing diff:");
151153
152154 args.insert(0, "--diff".as_ref());
153 let _ = py_runner(py_path.as_ref().unwrap(), "black", &args);
155 let _ = py_runner(py_path.as_ref().unwrap(), true, None, "black", &args);
156 }
157 // Rethrow error
158 let _ = res?;
159 }
160
161 if cpp_fmt {
162 let mut cfg_args_clang_format = cfg_args.clone();
163 let mut file_args_clang_format = file_args.clone();
164 let config_path = root_path.join(".clang-format");
165 let config_file_arg = format!("file:{}", config_path.display());
166 cfg_args_clang_format.extend(&["--style".as_ref(), config_file_arg.as_ref()]);
167 if bless {
168 eprintln!("formatting C++ files");
169 cfg_args_clang_format.push("-i".as_ref());
170 } else {
171 eprintln!("checking C++ file formatting");
172 cfg_args_clang_format.extend(&["--dry-run".as_ref(), "--Werror".as_ref()]);
173 }
174 let files;
175 if file_args_clang_format.is_empty() {
176 let llvm_wrapper = root_path.join("compiler/rustc_llvm/llvm-wrapper");
177 files = find_with_extension(
178 root_path,
179 Some(llvm_wrapper.as_path()),
180 &[OsStr::new("h"), OsStr::new("cpp")],
181 )?;
182 file_args_clang_format.extend(files.iter().map(|p| p.as_os_str()));
183 }
184 let args = merge_args(&cfg_args_clang_format, &file_args_clang_format);
185 let res = py_runner(py_path.as_ref().unwrap(), false, None, "clang-format", &args);
186
187 if res.is_err() && show_diff {
188 eprintln!("\nclang-format linting failed! Printing diff suggestions:");
189
190 let mut cfg_args_clang_format_diff = cfg_args.clone();
191 cfg_args_clang_format_diff.extend(&["--style".as_ref(), config_file_arg.as_ref()]);
192 for file in file_args_clang_format {
193 let mut formatted = String::new();
194 let mut diff_args = cfg_args_clang_format_diff.clone();
195 diff_args.push(file);
196 let _ = py_runner(
197 py_path.as_ref().unwrap(),
198 false,
199 Some(&mut formatted),
200 "clang-format",
201 &diff_args,
202 );
203 if formatted.is_empty() {
204 eprintln!(
205 "failed to obtain the formatted content for '{}'",
206 file.to_string_lossy()
207 );
208 continue;
209 }
210 let actual = std::fs::read_to_string(file).unwrap_or_else(|e| {
211 panic!(
212 "failed to read the C++ file at '{}' due to '{e}'",
213 file.to_string_lossy()
214 )
215 });
216 if formatted != actual {
217 let diff = similar::TextDiff::from_lines(&actual, &formatted);
218 eprintln!(
219 "{}",
220 diff.unified_diff().context_radius(4).header(
221 &format!("{} (actual)", file.to_string_lossy()),
222 &format!("{} (formatted)", file.to_string_lossy())
223 )
224 );
225 }
226 }
154227 }
155228 // Rethrow error
156229 let _ = res?;
......@@ -162,7 +235,7 @@ fn check_impl(
162235 let mut file_args_shc = file_args.clone();
163236 let files;
164237 if file_args_shc.is_empty() {
165 files = find_with_extension(root_path, "sh")?;
238 files = find_with_extension(root_path, None, &[OsStr::new("sh")])?;
166239 file_args_shc.extend(files.iter().map(|p| p.as_os_str()));
167240 }
168241
......@@ -181,8 +254,31 @@ fn merge_args<'a>(cfg_args: &[&'a OsStr], file_args: &[&'a OsStr]) -> Vec<&'a Os
181254}
182255
183256/// Run a python command with given arguments. `py_path` should be a virtualenv.
184fn py_runner(py_path: &Path, bin: &'static str, args: &[&OsStr]) -> Result<(), Error> {
185 let status = Command::new(py_path).arg("-m").arg(bin).args(args).status()?;
257///
258/// Captures `stdout` to a string if provided, otherwise prints the output.
259fn py_runner(
260 py_path: &Path,
261 as_module: bool,
262 stdout: Option<&mut String>,
263 bin: &'static str,
264 args: &[&OsStr],
265) -> Result<(), Error> {
266 let mut cmd = Command::new(py_path);
267 if as_module {
268 cmd.arg("-m").arg(bin).args(args);
269 } else {
270 let bin_path = py_path.with_file_name(bin);
271 cmd.arg(bin_path).args(args);
272 }
273 let status = if let Some(stdout) = stdout {
274 let output = cmd.output()?;
275 if let Ok(s) = std::str::from_utf8(&output.stdout) {
276 stdout.push_str(s);
277 }
278 output.status
279 } else {
280 cmd.status()?
281 };
186282 if status.success() { Ok(()) } else { Err(Error::FailedCheck(bin)) }
187283}
188284
......@@ -357,7 +453,11 @@ fn shellcheck_runner(args: &[&OsStr]) -> Result<(), Error> {
357453}
358454
359455/// Check git for tracked files matching an extension
360fn find_with_extension(root_path: &Path, extension: &str) -> Result<Vec<PathBuf>, Error> {
456fn find_with_extension(
457 root_path: &Path,
458 find_dir: Option<&Path>,
459 extensions: &[&OsStr],
460) -> Result<Vec<PathBuf>, Error> {
361461 // Untracked files show up for short status and are indicated with a leading `?`
362462 // -C changes git to be as if run from that directory
363463 let stat_output =
......@@ -368,15 +468,25 @@ fn find_with_extension(root_path: &Path, extension: &str) -> Result<Vec<PathBuf>
368468 }
369469
370470 let mut output = Vec::new();
371 let binding = Command::new("git").arg("-C").arg(root_path).args(["ls-files"]).output()?;
471 let binding = {
472 let mut command = Command::new("git");
473 command.arg("-C").arg(root_path).args(["ls-files"]);
474 if let Some(find_dir) = find_dir {
475 command.arg(find_dir);
476 }
477 command.output()?
478 };
372479 let tracked = String::from_utf8_lossy(&binding.stdout);
373480
374481 for line in tracked.lines() {
375482 let line = line.trim();
376483 let path = Path::new(line);
377484
378 if path.extension() == Some(OsStr::new(extension)) {
379 output.push(path.to_owned());
485 let Some(ref extension) = path.extension() else {
486 continue;
487 };
488 if extensions.contains(extension) {
489 output.push(root_path.join(path));
380490 }
381491 }
382492