1//===-- OrcIncrementalExecutorBuilder.cpp - ORC Builder --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the builder for ORC incremental execution.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Interpreter/OrcIncrementalExecutorBuilder.h"
14#include "OrcIncrementalExecutor.h"
15
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Config/config.h"
18#include "clang/Driver/Compilation.h"
19#include "clang/Driver/Driver.h"
20#include "clang/Driver/ToolChain.h"
21#include "clang/Interpreter/Interpreter.h"
22
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/Twine.h"
27
28#include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
29#include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h"
30#include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"
31#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
32#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
33#include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h"
34#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
35#include "llvm/ExecutionEngine/Orc/LLJIT.h"
36#include "llvm/ExecutionEngine/Orc/MapperJITLinkMemoryManager.h"
37#include "llvm/ExecutionEngine/Orc/Shared/SimpleRemoteEPCUtils.h"
38#include "llvm/ExecutionEngine/Orc/SharedMemoryMapSPS.h"
39#include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h"
40
41#include "llvm/Support/Error.h"
42#include "llvm/Support/FileSystem.h"
43#include "llvm/Support/FormatVariadic.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/raw_ostream.h"
46
47#include "llvm/TargetParser/Host.h"
48
49#include <array>
50#include <functional>
51#include <memory>
52#include <optional>
53#include <string>
54#include <utility>
55
56#ifdef LLVM_ON_UNIX
57#include <netdb.h>
58#include <netinet/in.h>
59#include <sys/socket.h>
60#include <unistd.h>
61#endif
62
63// Address of the host's emulated-TLS runtime entry point, or null if the host
64// cannot provide one. clang-repl's JIT always lowers thread_local to emulated
65// TLS (JITTargetMachineBuilder forces EmulatedTLS on), so JIT'd code references
66// __emutls_get_address on every target. That symbol lives in the compiler
67// runtime -- libgcc_s.so on a glibc toolchain, or the compiler-rt builtins
68// static archive on Darwin and on compiler-rt-rtlib toolchains. When it is only
69// in a static archive and nothing else references it, it is never linked in and
70// ORC's process-symbol lookup cannot resolve it. Referencing it here
71// force-links the archive member so it is present regardless of how the host
72// provides it. Defined if available at configure time
73// (CLANG_HAVE_EMUTLS_GET_ADDRESS). When unavailable, thread_locals instead rely
74// on process-symbol lookup.
75#if CLANG_HAVE_EMUTLS_GET_ADDRESS
76extern "C" void *__emutls_get_address(void *);
77static void *getEmuTLSGetAddressPtr() {
78 return reinterpret_cast<void *>(&__emutls_get_address);
79}
80#else
81static void *getEmuTLSGetAddressPtr() { return nullptr; }
82#endif
83
84namespace clang {
85OrcIncrementalExecutorBuilder::OrcIncrementalExecutorBuilder() = default;
86OrcIncrementalExecutorBuilder::~OrcIncrementalExecutorBuilder() = default;
87
88std::unique_ptr<IncrementalExecutorBuilder>
89IncrementalExecutorBuilder::createDefault() {
90 return std::make_unique<OrcIncrementalExecutorBuilder>();
91}
92
93llvm::Error
94OrcIncrementalExecutorBuilder::configure(IncrementalCompilerBuilder &CB,
95 const Options &Opts) {
96 IsOutOfProcess = Opts.IsOutOfProcess;
97 OOPExecutor = Opts.ExecutorPath;
98 OrcRuntimePath = Opts.RuntimePath;
99 if (OrcRuntimePath.empty())
100 CB.SetDriverCompilationCallback(UpdateOrcRuntimePathCB);
101 SlabAllocateSize = Opts.SlabAllocateSize;
102 UseSharedMemory = Opts.UseSharedMemory;
103 return llvm::Error::success();
104}
105
106bool OrcIncrementalExecutorBuilder::supportsJIT() const {
107 auto Triple = getHostJITTriple();
108 if (!Triple) {
109 llvm::consumeError(Err: Triple.takeError());
110 return false;
111 }
112 return true;
113}
114
115llvm::Expected<llvm::Triple>
116OrcIncrementalExecutorBuilder::getHostJITTriple() const {
117 auto J = llvm::orc::LLJITBuilder().create();
118 if (!J)
119 return J.takeError();
120 return (*J)->getTargetTriple();
121}
122
123static llvm::Expected<llvm::orc::JITTargetMachineBuilder>
124createJITTargetMachineBuilder(const llvm::Triple &TT) {
125 if (TT.getTriple() == llvm::sys::getProcessTriple())
126 // This fails immediately if the target backend is not registered
127 return llvm::orc::JITTargetMachineBuilder::detectHost();
128
129 // If the target backend is not registered, LLJITBuilder::create() will fail
130 return llvm::orc::JITTargetMachineBuilder(TT);
131}
132
133static llvm::Expected<std::unique_ptr<llvm::orc::LLJITBuilder>>
134createDefaultJITBuilder(llvm::orc::JITTargetMachineBuilder JTMB) {
135 auto JITBuilder = std::make_unique<llvm::orc::LLJITBuilder>();
136 JITBuilder->setJITTargetMachineBuilder(std::move(JTMB));
137 JITBuilder->setPrePlatformSetup([](llvm::orc::LLJIT &J) {
138 // Try to enable debugging of JIT'd code (only works with JITLink for
139 // ELF and MachO).
140 consumeError(Err: llvm::orc::enableDebuggerSupport(J));
141 return llvm::Error::success();
142 });
143 return std::move(JITBuilder);
144}
145
146Expected<std::unique_ptr<llvm::jitlink::JITLinkMemoryManager>>
147createSharedMemoryManager(llvm::orc::ExecutorProcessControl &EPC,
148 unsigned SlabAllocateSize) {
149 auto &ES = EPC.getExecutionSession();
150 auto B = llvm::orc::sps::createSharedMemoryMapBindings(ES);
151 if (!B)
152 return B.takeError();
153
154 size_t SlabSize;
155 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows())
156 SlabSize = 1024 * 1024;
157 else
158 SlabSize = 1024 * 1024 * 1024;
159
160 if (SlabAllocateSize > 0)
161 SlabSize = SlabAllocateSize;
162
163 return llvm::orc::MapperJITLinkMemoryManager::CreateWithMapper<
164 llvm::orc::SharedMemoryMapper>(ReservationGranularity: SlabSize, A&: ES, A: std::move(*B));
165}
166
167static llvm::Expected<
168 std::pair<std::unique_ptr<llvm::orc::SimpleRemoteEPC>, uint32_t>>
169launchExecutor(llvm::StringRef ExecutablePath,
170 std::function<void()> CustomizeFork) {
171#ifndef LLVM_ON_UNIX
172 // FIXME: Add support for Windows.
173 return llvm::make_error<llvm::StringError>(
174 "-" + ExecutablePath + " not supported on non-unix platforms",
175 llvm::inconvertibleErrorCode());
176#elif !LLVM_ENABLE_THREADS
177 // Out of process mode using SimpleRemoteEPC depends on threads.
178 return llvm::make_error<llvm::StringError>(
179 "-" + ExecutablePath +
180 " requires threads, but LLVM was built with "
181 "LLVM_ENABLE_THREADS=Off",
182 llvm::inconvertibleErrorCode());
183#else
184
185 if (!llvm::sys::fs::can_execute(Path: ExecutablePath))
186 return llvm::make_error<llvm::StringError>(
187 Args: llvm::formatv(Fmt: "Specified executor invalid: {0}", Vals&: ExecutablePath),
188 Args: llvm::inconvertibleErrorCode());
189
190 constexpr int ReadEnd = 0;
191 constexpr int WriteEnd = 1;
192
193 // Pipe FDs.
194 int ToExecutor[2];
195 int FromExecutor[2];
196
197 uint32_t ChildPID;
198
199 // Create pipes to/from the executor..
200 if (pipe(pipedes: ToExecutor) != 0 || pipe(pipedes: FromExecutor) != 0)
201 return llvm::make_error<llvm::StringError>(
202 Args: "Unable to create pipe for executor", Args: llvm::inconvertibleErrorCode());
203
204 ChildPID = fork();
205
206 if (ChildPID == 0) {
207 // In the child...
208
209 // Close the parent ends of the pipes
210 close(fd: ToExecutor[WriteEnd]);
211 close(fd: FromExecutor[ReadEnd]);
212
213 if (CustomizeFork)
214 CustomizeFork();
215
216 // Execute the child process.
217 std::unique_ptr<char[]> ExecutorPath, FDSpecifier;
218 {
219 ExecutorPath = std::make_unique<char[]>(num: ExecutablePath.size() + 1);
220 strcpy(dest: ExecutorPath.get(), src: ExecutablePath.data());
221
222 std::string FDSpecifierStr("filedescs=");
223 FDSpecifierStr += llvm::utostr(X: ToExecutor[ReadEnd]);
224 FDSpecifierStr += ',';
225 FDSpecifierStr += llvm::utostr(X: FromExecutor[WriteEnd]);
226 FDSpecifier = std::make_unique<char[]>(num: FDSpecifierStr.size() + 1);
227 strcpy(dest: FDSpecifier.get(), src: FDSpecifierStr.c_str());
228 }
229
230 char *const Args[] = {ExecutorPath.get(), FDSpecifier.get(), nullptr};
231 int RC = execvp(file: ExecutorPath.get(), argv: Args);
232 if (RC != 0) {
233 llvm::errs() << "unable to launch out-of-process executor \""
234 << ExecutorPath.get() << "\"\n";
235 exit(status: 1);
236 }
237 }
238 // else we're the parent...
239
240 // Close the child ends of the pipes
241 close(fd: ToExecutor[ReadEnd]);
242 close(fd: FromExecutor[WriteEnd]);
243
244 auto EPCOrErr =
245 llvm::orc::SimpleRemoteEPC::Create<llvm::orc::FDSimpleRemoteEPCTransport>(
246 D: std::make_unique<llvm::orc::DynamicThreadPoolTaskDispatcher>(
247 args: std::nullopt),
248 TransportTCtorArgs&: FromExecutor[ReadEnd], TransportTCtorArgs&: ToExecutor[WriteEnd]);
249 if (!EPCOrErr)
250 return EPCOrErr.takeError();
251 return std::make_pair(x: std::move(*EPCOrErr), y&: ChildPID);
252#endif
253}
254
255#if LLVM_ON_UNIX && LLVM_ENABLE_THREADS
256
257static Expected<int> connectTCPSocketImpl(std::string Host,
258 std::string PortStr) {
259 addrinfo *AI;
260 addrinfo Hints{};
261 Hints.ai_family = AF_INET;
262 Hints.ai_socktype = SOCK_STREAM;
263 Hints.ai_flags = AI_NUMERICSERV;
264
265 if (int EC = getaddrinfo(name: Host.c_str(), service: PortStr.c_str(), req: &Hints, pai: &AI))
266 return llvm::make_error<llvm::StringError>(
267 Args: llvm::formatv(Fmt: "address resolution failed ({0})", Vals: strerror(errnum: EC)),
268 Args: llvm::inconvertibleErrorCode());
269 // Cycle through the returned addrinfo structures and connect to the first
270 // reachable endpoint.
271 int SockFD;
272 addrinfo *Server;
273 for (Server = AI; Server != nullptr; Server = Server->ai_next) {
274 // socket might fail, e.g. if the address family is not supported. Skip to
275 // the next addrinfo structure in such a case.
276 if ((SockFD = socket(domain: AI->ai_family, type: AI->ai_socktype, protocol: AI->ai_protocol)) < 0)
277 continue;
278
279 // If connect returns null, we exit the loop with a working socket.
280 if (connect(fd: SockFD, addr: Server->ai_addr, len: Server->ai_addrlen) == 0)
281 break;
282
283 close(fd: SockFD);
284 }
285 freeaddrinfo(ai: AI);
286
287 // If we reached the end of the loop without connecting to a valid endpoint,
288 // dump the last error that was logged in socket() or connect().
289 if (Server == nullptr)
290 return llvm::make_error<llvm::StringError>(Args: "invalid hostname",
291 Args: llvm::inconvertibleErrorCode());
292
293 return SockFD;
294}
295
296static llvm::Expected<std::unique_ptr<llvm::orc::SimpleRemoteEPC>>
297connectTCPSocket(llvm::StringRef NetworkAddress) {
298#ifndef LLVM_ON_UNIX
299 // FIXME: Add TCP support for Windows.
300 return llvm::make_error<llvm::StringError>(
301 "-" + NetworkAddress + " not supported on non-unix platforms",
302 llvm::inconvertibleErrorCode());
303#elif !LLVM_ENABLE_THREADS
304 // Out of process mode using SimpleRemoteEPC depends on threads.
305 return llvm::make_error<llvm::StringError>(
306 "-" + NetworkAddress +
307 " requires threads, but LLVM was built with "
308 "LLVM_ENABLE_THREADS=Off",
309 llvm::inconvertibleErrorCode());
310#else
311
312 auto CreateErr = [NetworkAddress](Twine Details) {
313 return llvm::make_error<llvm::StringError>(
314 Args: formatv(Fmt: "Failed to connect TCP socket '{0}': {1}", Vals: NetworkAddress,
315 Vals&: Details),
316 Args: llvm::inconvertibleErrorCode());
317 };
318
319 StringRef Host, PortStr;
320 std::tie(args&: Host, args&: PortStr) = NetworkAddress.split(Separator: ':');
321 if (Host.empty())
322 return CreateErr("Host name for -" + NetworkAddress + " can not be empty");
323 if (PortStr.empty())
324 return CreateErr("Port number in -" + NetworkAddress + " can not be empty");
325 int Port = 0;
326 if (PortStr.getAsInteger(Radix: 10, Result&: Port))
327 return CreateErr("Port number '" + PortStr + "' is not a valid integer");
328
329 Expected<int> SockFD = connectTCPSocketImpl(Host: Host.str(), PortStr: PortStr.str());
330 if (!SockFD)
331 return SockFD.takeError();
332
333 return llvm::orc::SimpleRemoteEPC::Create<
334 llvm::orc::FDSimpleRemoteEPCTransport>(
335 D: std::make_unique<llvm::orc::DynamicThreadPoolTaskDispatcher>(
336 args: std::nullopt),
337 TransportTCtorArgs&: *SockFD, TransportTCtorArgs&: *SockFD);
338#endif
339}
340#endif // _WIN32
341
342static llvm::Expected<std::unique_ptr<llvm::orc::LLJITBuilder>>
343createLLJITBuilder(std::unique_ptr<llvm::orc::ExecutorProcessControl> EPC,
344 llvm::StringRef OrcRuntimePath) {
345 auto JTMB = createJITTargetMachineBuilder(TT: EPC->getTargetTriple());
346 if (!JTMB)
347 return JTMB.takeError();
348 auto JB = createDefaultJITBuilder(JTMB: std::move(*JTMB));
349 if (!JB)
350 return JB.takeError();
351
352 (*JB)->setExecutorProcessControl(std::move(EPC));
353 (*JB)->setPlatformSetUp(
354 llvm::orc::ExecutorNativePlatform(OrcRuntimePath.str()));
355
356 return std::move(*JB);
357}
358
359static llvm::Expected<
360 std::pair<std::unique_ptr<llvm::orc::LLJITBuilder>, uint32_t>>
361outOfProcessJITBuilder(
362 const OrcIncrementalExecutorBuilder &IncrExecutorBuilder) {
363 std::unique_ptr<llvm::orc::ExecutorProcessControl> EPC;
364 uint32_t childPid = -1;
365 if (!IncrExecutorBuilder.OOPExecutor.empty()) {
366 // Launch an out-of-process executor locally in a child process.
367 auto ResultOrErr = launchExecutor(ExecutablePath: IncrExecutorBuilder.OOPExecutor,
368 CustomizeFork: IncrExecutorBuilder.CustomizeFork);
369 if (!ResultOrErr)
370 return ResultOrErr.takeError();
371 childPid = ResultOrErr->second;
372 auto EPCOrErr = std::move(ResultOrErr->first);
373 EPC = std::move(EPCOrErr);
374 } else if (IncrExecutorBuilder.OOPExecutorConnect != "") {
375#if LLVM_ON_UNIX && LLVM_ENABLE_THREADS
376 auto EPCOrErr = connectTCPSocket(NetworkAddress: IncrExecutorBuilder.OOPExecutorConnect);
377 if (!EPCOrErr)
378 return EPCOrErr.takeError();
379 EPC = std::move(*EPCOrErr);
380#else
381 return llvm::make_error<llvm::StringError>(
382 "Out-of-process JIT over TCP is not supported on this platform",
383 std::error_code());
384#endif
385 }
386
387 std::unique_ptr<llvm::orc::LLJITBuilder> JB;
388 if (EPC) {
389 auto JBOrErr =
390 createLLJITBuilder(EPC: std::move(EPC), OrcRuntimePath: IncrExecutorBuilder.OrcRuntimePath);
391 if (!JBOrErr)
392 return JBOrErr.takeError();
393 JB = std::move(*JBOrErr);
394
395 if (IncrExecutorBuilder.UseSharedMemory)
396 JB->setMemoryManagerCreator(
397 [SlabAllocateSize = IncrExecutorBuilder.SlabAllocateSize](
398 llvm::orc::ExecutionSession &ES) {
399 return createSharedMemoryManager(EPC&: ES.getExecutorProcessControl(),
400 SlabAllocateSize);
401 });
402 }
403
404 return std::make_pair(x: std::move(JB), y&: childPid);
405}
406
407llvm::Expected<std::unique_ptr<IncrementalExecutor>>
408OrcIncrementalExecutorBuilder::createExecutor(llvm::orc::ThreadSafeContext &TSC,
409 const clang::TargetInfo &TI) {
410 llvm::Triple TT = TI.getTriple();
411 if (!TT.isOSWindows() && IsOutOfProcess) {
412 if (!JITBuilder) {
413 auto ResOrErr = outOfProcessJITBuilder(IncrExecutorBuilder: *this);
414 if (!ResOrErr)
415 return ResOrErr.takeError();
416 JITBuilder = std::move(ResOrErr->first);
417 ExecutorPID = ResOrErr->second;
418 }
419 if (!JITBuilder)
420 return llvm::make_error<llvm::StringError>(
421 Args: "Operation failed. No LLJITBuilder for out-of-process JIT",
422 Args: std::error_code());
423 }
424
425 if (!JITBuilder) {
426 auto JTMB = createJITTargetMachineBuilder(TT);
427 if (!JTMB)
428 return JTMB.takeError();
429 if (CM)
430 JTMB->setCodeModel(CM);
431 auto JB = createDefaultJITBuilder(JTMB: std::move(*JTMB));
432 if (!JB)
433 return JB.takeError();
434 JITBuilder = std::move(*JB);
435 // TODO: Switch to native TLS once clang-repl can adopt the ORC runtime
436 // (which provides __emutls_get_address and supports the full TLS
437 // lifecycle). That will also remove the in-process-only constraint below.
438 //
439 // clang-repl lowers thread_local to emulated TLS on every target (see
440 // JITTargetMachineBuilder), so JIT'd code calls __emutls_get_address. When
441 // the host cannot resolve that symbol through process-symbol lookup
442 // (Darwin, and ELF toolchains that link compiler-rt builtins rather than
443 // libgcc_s), define the force-linked host symbol (see
444 // getEmuTLSGetAddressPtr) as an absolute symbol so it is visible to JIT'd
445 // code. This is harmless where process-symbol lookup would already resolve
446 // it: an already-defined symbol shadows the process-symbols generator.
447 // In-process execution only -- the host address is meaningless in an
448 // out-of-process executor.
449 if (void *EmuTLSGetAddress = getEmuTLSGetAddressPtr())
450 JITBuilder->setNotifyCreatedCallback(
451 [EmuTLSGetAddress](llvm::orc::LLJIT &J) {
452 auto &JD = J.getProcessSymbolsJITDylib()
453 ? *J.getProcessSymbolsJITDylib()
454 : J.getMainJITDylib();
455 return JD.define(MU: llvm::orc::absoluteSymbols(
456 Symbols: {{J.mangleAndIntern(UnmangledName: "__emutls_get_address"),
457 {llvm::orc::ExecutorAddr::fromPtr(Ptr: EmuTLSGetAddress),
458 llvm::JITSymbolFlags::Exported}}}));
459 });
460 }
461
462 // Point the JIT's TargetMachine at the LLVMContext's -mllvm library options.
463 // A builder without a JTMB, which LLJIT detects later, keeps the defaults.
464 std::optional<llvm::orc::JITTargetMachineBuilder> &JTMB =
465 JITBuilder->getJITTargetMachineBuilder();
466 if (JTMB && !JTMB->getOptions().MCOptions.LibraryOptions)
467 TSC.withContextDo(F: [&](llvm::LLVMContext *Ctx) {
468 JTMB->getOptions().MCOptions.LibraryOptions = &Ctx->getLibraryOptions();
469 });
470
471 llvm::Error Err = llvm::Error::success();
472 std::unique_ptr<IncrementalExecutor> Executor =
473 std::make_unique<OrcIncrementalExecutor>(args&: TSC, args&: *JITBuilder, args&: Err);
474
475 if (Err)
476 return std::move(Err);
477
478 return std::move(Executor);
479}
480
481llvm::Error OrcIncrementalExecutorBuilder::UpdateOrcRuntimePath(
482 const clang::driver::Compilation &C) {
483 if (!IsOutOfProcess)
484 return llvm::Error::success();
485
486 const clang::driver::Driver &D = C.getDriver();
487 const clang::driver::ToolChain &TC = C.getDefaultToolChain();
488
489 llvm::SmallVector<std::string, 2> OrcRTLibNames;
490
491 // Get canonical compiler-rt path
492 std::string CompilerRTPath = TC.getCompilerRT(Args: C.getArgs(), Component: "orc_rt");
493 llvm::StringRef CanonicalFilename = llvm::sys::path::filename(path: CompilerRTPath);
494
495 if (CanonicalFilename.empty()) {
496 return llvm::make_error<llvm::StringError>(
497 Args: "Could not determine OrcRuntime filename from ToolChain",
498 Args: llvm::inconvertibleErrorCode());
499 }
500
501 OrcRTLibNames.push_back(Elt: CanonicalFilename.str());
502
503 // Derive legacy spelling (libclang_rt.orc_rt -> orc_rt)
504 llvm::StringRef LegacySuffix = CanonicalFilename;
505 if (LegacySuffix.consume_front(Prefix: "libclang_rt.")) {
506 OrcRTLibNames.push_back(Elt: ("lib" + LegacySuffix).str());
507 }
508
509 // Extract directory
510 llvm::SmallString<256> OrcRTDir(CompilerRTPath);
511 llvm::sys::path::remove_filename(path&: OrcRTDir);
512
513 llvm::SmallVector<std::string, 8> triedPaths;
514
515 auto findInDir = [&](llvm::StringRef Dir) -> std::optional<std::string> {
516 for (const auto &LibName : OrcRTLibNames) {
517 llvm::SmallString<256> FullPath = Dir;
518 llvm::sys::path::append(path&: FullPath, a: LibName);
519 if (llvm::sys::fs::exists(Path: FullPath))
520 return std::string(FullPath.str());
521 triedPaths.push_back(Elt: std::string(FullPath.str()));
522 }
523 return std::nullopt;
524 };
525
526 // Try the primary directory first
527 if (auto Found = findInDir(OrcRTDir)) {
528 OrcRuntimePath = *Found;
529 return llvm::Error::success();
530 }
531
532 // We want to find the relative path from the Driver to the OrcRTDir
533 // to replicate that structure elsewhere if needed.
534 llvm::StringRef Rel = OrcRTDir.str();
535 if (!Rel.consume_front(Prefix: llvm::sys::path::parent_path(path: D.Dir))) {
536 return llvm::make_error<llvm::StringError>(
537 Args: llvm::formatv(Fmt: "OrcRuntime library path ({0}) is not located within the "
538 "Clang resource directory ({1}). Check your installation "
539 "or provide an explicit path via -resource-dir.",
540 Vals&: OrcRTDir, Vals: D.Dir)
541 .str(),
542 Args: llvm::inconvertibleErrorCode());
543 }
544
545 // Generic Backward Search (Climbing the tree)
546 // This is useful for unit tests or relocated toolchains
547 llvm::SmallString<256> Cursor(D.Dir); // Start from the driver directory
548 while (llvm::sys::path::has_parent_path(path: Cursor)) {
549 Cursor = llvm::sys::path::parent_path(path: Cursor).str();
550 llvm::SmallString<256> Candidate = Cursor;
551 llvm::sys::path::append(path&: Candidate, a: Rel);
552
553 if (auto Found = findInDir(Candidate)) {
554 OrcRuntimePath = *Found;
555 return llvm::Error::success();
556 }
557
558 // Safety check
559 if (triedPaths.size() > 32)
560 break;
561 }
562
563 // Build a helpful error string
564 std::string Joined;
565 for (size_t i = 0; i < triedPaths.size(); ++i) {
566 if (i > 0)
567 Joined += "\n ";
568 Joined += triedPaths[i];
569 }
570
571 return llvm::make_error<llvm::StringError>(
572 Args: llvm::formatv(Fmt: "OrcRuntime library not found. Checked: {0}",
573 Vals: Joined.empty() ? "<none>" : Joined)
574 .str(),
575 Args: std::make_error_code(e: std::errc::no_such_file_or_directory));
576}
577
578} // end namespace clang
579