1 //===----------- CoreAPIsTest.cpp - Unit tests for Core ORC APIs ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "OrcTestCommon.h"
11 #include "llvm/Config/llvm-config.h"
12 #include "llvm/ExecutionEngine/Orc/Core.h"
13 #include "llvm/ExecutionEngine/Orc/OrcError.h"
14 
15 #include <set>
16 #include <thread>
17 
18 using namespace llvm;
19 using namespace llvm::orc;
20 
21 class CoreAPIsStandardTest : public CoreAPIsBasedStandardTest {};
22 
23 namespace {
24 
25 class SimpleMaterializationUnit : public MaterializationUnit {
26 public:
27   using MaterializeFunction =
28       std::function<void(MaterializationResponsibility)>;
29   using DiscardFunction =
30       std::function<void(const JITDylib &, SymbolStringPtr)>;
31   using DestructorFunction = std::function<void()>;
32 
33   SimpleMaterializationUnit(
34       SymbolFlagsMap SymbolFlags, MaterializeFunction Materialize,
35       DiscardFunction Discard = DiscardFunction(),
36       DestructorFunction Destructor = DestructorFunction())
37       : MaterializationUnit(std::move(SymbolFlags)),
38         Materialize(std::move(Materialize)), Discard(std::move(Discard)),
39         Destructor(std::move(Destructor)) {}
40 
41   ~SimpleMaterializationUnit() override {
42     if (Destructor)
43       Destructor();
44   }
45 
46   void materialize(MaterializationResponsibility R) override {
47     Materialize(std::move(R));
48   }
49 
50   void discard(const JITDylib &JD, SymbolStringPtr Name) override {
51     if (Discard)
52       Discard(JD, std::move(Name));
53     else
54       llvm_unreachable("Discard not supported");
55   }
56 
57 private:
58   MaterializeFunction Materialize;
59   DiscardFunction Discard;
60   DestructorFunction Destructor;
61 };
62 
63 TEST_F(CoreAPIsStandardTest, BasicSuccessfulLookup) {
64   bool OnResolutionRun = false;
65   bool OnReadyRun = false;
66 
67   auto OnResolution = [&](Expected<SymbolMap> Result) {
68     EXPECT_TRUE(!!Result) << "Resolution unexpectedly returned error";
69     auto &Resolved = *Result;
70     auto I = Resolved.find(Foo);
71     EXPECT_NE(I, Resolved.end()) << "Could not find symbol definition";
72     EXPECT_EQ(I->second.getAddress(), FooAddr)
73         << "Resolution returned incorrect result";
74     OnResolutionRun = true;
75   };
76   auto OnReady = [&](Error Err) {
77     cantFail(std::move(Err));
78     OnReadyRun = true;
79   };
80 
81   std::shared_ptr<MaterializationResponsibility> FooMR;
82 
83   cantFail(JD.define(llvm::make_unique<SimpleMaterializationUnit>(
84       SymbolFlagsMap({{Foo, FooSym.getFlags()}}),
85       [&](MaterializationResponsibility R) {
86         FooMR = std::make_shared<MaterializationResponsibility>(std::move(R));
87       })));
88 
89   ES.lookup({&JD}, {Foo}, OnResolution, OnReady, NoDependenciesToRegister);
90 
91   EXPECT_FALSE(OnResolutionRun) << "Should not have been resolved yet";
92   EXPECT_FALSE(OnReadyRun) << "Should not have been marked ready yet";
93 
94   FooMR->resolve({{Foo, FooSym}});
95 
96   EXPECT_TRUE(OnResolutionRun) << "Should have been resolved";
97   EXPECT_FALSE(OnReadyRun) << "Should not have been marked ready yet";
98 
99   FooMR->emit();
100 
101   EXPECT_TRUE(OnReadyRun) << "Should have been marked ready";
102 }
103 
104 TEST_F(CoreAPIsStandardTest, ExecutionSessionFailQuery) {
105   bool OnResolutionRun = false;
106   bool OnReadyRun = false;
107 
108   auto OnResolution = [&](Expected<SymbolMap> Result) {
109     EXPECT_FALSE(!!Result) << "Resolution unexpectedly returned success";
110     auto Msg = toString(Result.takeError());
111     EXPECT_EQ(Msg, "xyz") << "Resolution returned incorrect result";
112     OnResolutionRun = true;
113   };
114   auto OnReady = [&](Error Err) {
115     cantFail(std::move(Err));
116     OnReadyRun = true;
117   };
118 
119   AsynchronousSymbolQuery Q(SymbolNameSet({Foo}), OnResolution, OnReady);
120 
121   ES.legacyFailQuery(Q,
122                      make_error<StringError>("xyz", inconvertibleErrorCode()));
123 
124   EXPECT_TRUE(OnResolutionRun) << "OnResolutionCallback was not run";
125   EXPECT_FALSE(OnReadyRun) << "OnReady unexpectedly run";
126 }
127 
128 TEST_F(CoreAPIsStandardTest, EmptyLookup) {
129   bool OnResolvedRun = false;
130   bool OnReadyRun = false;
131 
132   auto OnResolution = [&](Expected<SymbolMap> Result) {
133     cantFail(std::move(Result));
134     OnResolvedRun = true;
135   };
136 
137   auto OnReady = [&](Error Err) {
138     cantFail(std::move(Err));
139     OnReadyRun = true;
140   };
141 
142   ES.lookup({&JD}, {}, OnResolution, OnReady, NoDependenciesToRegister);
143 
144   EXPECT_TRUE(OnResolvedRun) << "OnResolved was not run for empty query";
145   EXPECT_TRUE(OnReadyRun) << "OnReady was not run for empty query";
146 }
147 
148 TEST_F(CoreAPIsStandardTest, ChainedJITDylibLookup) {
149   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
150 
151   auto &JD2 = ES.createJITDylib("JD2");
152 
153   bool OnResolvedRun = false;
154   bool OnReadyRun = false;
155 
156   auto Q = std::make_shared<AsynchronousSymbolQuery>(
157       SymbolNameSet({Foo}),
158       [&](Expected<SymbolMap> Result) {
159         cantFail(std::move(Result));
160         OnResolvedRun = true;
161       },
162       [&](Error Err) {
163         cantFail(std::move(Err));
164         OnReadyRun = true;
165       });
166 
167   JD2.legacyLookup(Q, JD.legacyLookup(Q, {Foo}));
168 
169   EXPECT_TRUE(OnResolvedRun) << "OnResolved was not run for empty query";
170   EXPECT_TRUE(OnReadyRun) << "OnReady was not run for empty query";
171 }
172 
173 TEST_F(CoreAPIsStandardTest, LookupFlagsTest) {
174   // Test that lookupFlags works on a predefined symbol, and does not trigger
175   // materialization of a lazy symbol. Make the lazy symbol weak to test that
176   // the weak flag is propagated correctly.
177 
178   BarSym.setFlags(static_cast<JITSymbolFlags::FlagNames>(
179       JITSymbolFlags::Exported | JITSymbolFlags::Weak));
180   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
181       SymbolFlagsMap({{Bar, BarSym.getFlags()}}),
182       [](MaterializationResponsibility R) {
183         llvm_unreachable("Symbol materialized on flags lookup");
184       });
185 
186   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
187   cantFail(JD.define(std::move(MU)));
188 
189   SymbolNameSet Names({Foo, Bar, Baz});
190 
191   auto SymbolFlags = JD.lookupFlags(Names);
192 
193   EXPECT_EQ(SymbolFlags.size(), 2U)
194       << "Returned symbol flags contains unexpected results";
195   EXPECT_EQ(SymbolFlags.count(Foo), 1U) << "Missing lookupFlags result for Foo";
196   EXPECT_EQ(SymbolFlags[Foo], FooSym.getFlags())
197       << "Incorrect flags returned for Foo";
198   EXPECT_EQ(SymbolFlags.count(Bar), 1U)
199       << "Missing  lookupFlags result for Bar";
200   EXPECT_EQ(SymbolFlags[Bar], BarSym.getFlags())
201       << "Incorrect flags returned for Bar";
202 }
203 
204 TEST_F(CoreAPIsStandardTest, TestBasicAliases) {
205   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}, {Bar, BarSym}})));
206   cantFail(JD.define(symbolAliases({{Baz, {Foo, JITSymbolFlags::Exported}},
207                                     {Qux, {Bar, JITSymbolFlags::Weak}}})));
208   cantFail(JD.define(absoluteSymbols({{Qux, QuxSym}})));
209 
210   auto Result = lookup({&JD}, {Baz, Qux});
211   EXPECT_TRUE(!!Result) << "Unexpected lookup failure";
212   EXPECT_EQ(Result->count(Baz), 1U) << "No result for \"baz\"";
213   EXPECT_EQ(Result->count(Qux), 1U) << "No result for \"qux\"";
214   EXPECT_EQ((*Result)[Baz].getAddress(), FooSym.getAddress())
215       << "\"Baz\"'s address should match \"Foo\"'s";
216   EXPECT_EQ((*Result)[Qux].getAddress(), QuxSym.getAddress())
217       << "The \"Qux\" alias should have been overriden";
218 }
219 
220 TEST_F(CoreAPIsStandardTest, TestChainedAliases) {
221   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
222   cantFail(JD.define(symbolAliases(
223       {{Baz, {Bar, BazSym.getFlags()}}, {Bar, {Foo, BarSym.getFlags()}}})));
224 
225   auto Result = lookup({&JD}, {Bar, Baz});
226   EXPECT_TRUE(!!Result) << "Unexpected lookup failure";
227   EXPECT_EQ(Result->count(Bar), 1U) << "No result for \"bar\"";
228   EXPECT_EQ(Result->count(Baz), 1U) << "No result for \"baz\"";
229   EXPECT_EQ((*Result)[Bar].getAddress(), FooSym.getAddress())
230       << "\"Bar\"'s address should match \"Foo\"'s";
231   EXPECT_EQ((*Result)[Baz].getAddress(), FooSym.getAddress())
232       << "\"Baz\"'s address should match \"Foo\"'s";
233 }
234 
235 TEST_F(CoreAPIsStandardTest, TestBasicReExports) {
236   // Test that the basic use case of re-exporting a single symbol from another
237   // JITDylib works.
238   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
239 
240   auto &JD2 = ES.createJITDylib("JD2");
241 
242   cantFail(JD2.define(reexports(JD, {{Bar, {Foo, BarSym.getFlags()}}})));
243 
244   auto Result = cantFail(lookup({&JD2}, Bar));
245   EXPECT_EQ(Result.getAddress(), FooSym.getAddress())
246       << "Re-export Bar for symbol Foo should match FooSym's address";
247 }
248 
249 TEST_F(CoreAPIsStandardTest, TestThatReExportsDontUnnecessarilyMaterialize) {
250   // Test that re-exports do not materialize symbols that have not been queried
251   // for.
252   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
253 
254   bool BarMaterialized = false;
255   auto BarMU = llvm::make_unique<SimpleMaterializationUnit>(
256       SymbolFlagsMap({{Bar, BarSym.getFlags()}}),
257       [&](MaterializationResponsibility R) {
258         BarMaterialized = true;
259         R.resolve({{Bar, BarSym}});
260         R.emit();
261       });
262 
263   cantFail(JD.define(BarMU));
264 
265   auto &JD2 = ES.createJITDylib("JD2");
266 
267   cantFail(JD2.define(reexports(
268       JD, {{Baz, {Foo, BazSym.getFlags()}}, {Qux, {Bar, QuxSym.getFlags()}}})));
269 
270   auto Result = cantFail(lookup({&JD2}, Baz));
271   EXPECT_EQ(Result.getAddress(), FooSym.getAddress())
272       << "Re-export Baz for symbol Foo should match FooSym's address";
273 
274   EXPECT_FALSE(BarMaterialized) << "Bar should not have been materialized";
275 }
276 
277 TEST_F(CoreAPIsStandardTest, TestReexportsFallbackGenerator) {
278   // Test that a re-exports fallback generator can dynamically generate
279   // reexports.
280 
281   auto &JD2 = ES.createJITDylib("JD2");
282   cantFail(JD2.define(absoluteSymbols({{Foo, FooSym}, {Bar, BarSym}})));
283 
284   auto Filter = [this](SymbolStringPtr Name) { return Name != Bar; };
285 
286   JD.setFallbackDefinitionGenerator(
287       ReexportsFallbackDefinitionGenerator(JD2, Filter));
288 
289   auto Flags = JD.lookupFlags({Foo, Bar, Baz});
290   EXPECT_EQ(Flags.size(), 1U) << "Unexpected number of results";
291   EXPECT_EQ(Flags[Foo], FooSym.getFlags()) << "Unexpected flags for Foo";
292 
293   auto Result = cantFail(lookup({&JD}, Foo));
294 
295   EXPECT_EQ(Result.getAddress(), FooSym.getAddress())
296       << "Incorrect reexported symbol address";
297 }
298 
299 TEST_F(CoreAPIsStandardTest, TestTrivialCircularDependency) {
300   Optional<MaterializationResponsibility> FooR;
301   auto FooMU = llvm::make_unique<SimpleMaterializationUnit>(
302       SymbolFlagsMap({{Foo, FooSym.getFlags()}}),
303       [&](MaterializationResponsibility R) { FooR.emplace(std::move(R)); });
304 
305   cantFail(JD.define(FooMU));
306 
307   bool FooReady = false;
308   auto OnResolution = [](Expected<SymbolMap> R) { cantFail(std::move(R)); };
309   auto OnReady = [&](Error Err) {
310     cantFail(std::move(Err));
311     FooReady = true;
312   };
313 
314   ES.lookup({&JD}, {Foo}, std::move(OnResolution), std::move(OnReady),
315             NoDependenciesToRegister);
316 
317   FooR->resolve({{Foo, FooSym}});
318   FooR->emit();
319 
320   EXPECT_TRUE(FooReady)
321     << "Self-dependency prevented symbol from being marked ready";
322 }
323 
324 TEST_F(CoreAPIsStandardTest, TestCircularDependenceInOneJITDylib) {
325   // Test that a circular symbol dependency between three symbols in a JITDylib
326   // does not prevent any symbol from becoming 'ready' once all symbols are
327   // emitted.
328 
329   // Create three MaterializationResponsibility objects: one for each of Foo,
330   // Bar and Baz. These are optional because MaterializationResponsibility
331   // does not have a default constructor).
332   Optional<MaterializationResponsibility> FooR;
333   Optional<MaterializationResponsibility> BarR;
334   Optional<MaterializationResponsibility> BazR;
335 
336   // Create a MaterializationUnit for each symbol that moves the
337   // MaterializationResponsibility into one of the locals above.
338   auto FooMU = llvm::make_unique<SimpleMaterializationUnit>(
339       SymbolFlagsMap({{Foo, FooSym.getFlags()}}),
340       [&](MaterializationResponsibility R) { FooR.emplace(std::move(R)); });
341 
342   auto BarMU = llvm::make_unique<SimpleMaterializationUnit>(
343       SymbolFlagsMap({{Bar, BarSym.getFlags()}}),
344       [&](MaterializationResponsibility R) { BarR.emplace(std::move(R)); });
345 
346   auto BazMU = llvm::make_unique<SimpleMaterializationUnit>(
347       SymbolFlagsMap({{Baz, BazSym.getFlags()}}),
348       [&](MaterializationResponsibility R) { BazR.emplace(std::move(R)); });
349 
350   // Define the symbols.
351   cantFail(JD.define(FooMU));
352   cantFail(JD.define(BarMU));
353   cantFail(JD.define(BazMU));
354 
355   // Query each of the symbols to trigger materialization.
356   bool FooResolved = false;
357   bool FooReady = false;
358 
359   auto OnFooResolution = [&](Expected<SymbolMap> Result) {
360     cantFail(std::move(Result));
361     FooResolved = true;
362   };
363 
364   auto OnFooReady = [&](Error Err) {
365     cantFail(std::move(Err));
366     FooReady = true;
367   };
368 
369   // Issue a lookup for Foo. Use NoDependenciesToRegister: We're going to add
370   // the dependencies manually below.
371   ES.lookup({&JD}, {Foo}, std::move(OnFooResolution), std::move(OnFooReady),
372             NoDependenciesToRegister);
373 
374   bool BarResolved = false;
375   bool BarReady = false;
376   auto OnBarResolution = [&](Expected<SymbolMap> Result) {
377     cantFail(std::move(Result));
378     BarResolved = true;
379   };
380 
381   auto OnBarReady = [&](Error Err) {
382     cantFail(std::move(Err));
383     BarReady = true;
384   };
385 
386   ES.lookup({&JD}, {Bar}, std::move(OnBarResolution), std::move(OnBarReady),
387             NoDependenciesToRegister);
388 
389   bool BazResolved = false;
390   bool BazReady = false;
391 
392   auto OnBazResolution = [&](Expected<SymbolMap> Result) {
393     cantFail(std::move(Result));
394     BazResolved = true;
395   };
396 
397   auto OnBazReady = [&](Error Err) {
398     cantFail(std::move(Err));
399     BazReady = true;
400   };
401 
402   ES.lookup({&JD}, {Baz}, std::move(OnBazResolution), std::move(OnBazReady),
403             NoDependenciesToRegister);
404 
405   // Add a circular dependency: Foo -> Bar, Bar -> Baz, Baz -> Foo.
406   FooR->addDependenciesForAll({{&JD, SymbolNameSet({Bar})}});
407   BarR->addDependenciesForAll({{&JD, SymbolNameSet({Baz})}});
408   BazR->addDependenciesForAll({{&JD, SymbolNameSet({Foo})}});
409 
410   // Add self-dependencies for good measure. This tests that the implementation
411   // of addDependencies filters these out.
412   FooR->addDependenciesForAll({{&JD, SymbolNameSet({Foo})}});
413   BarR->addDependenciesForAll({{&JD, SymbolNameSet({Bar})}});
414   BazR->addDependenciesForAll({{&JD, SymbolNameSet({Baz})}});
415 
416   // Check that nothing has been resolved yet.
417   EXPECT_FALSE(FooResolved) << "\"Foo\" should not be resolved yet";
418   EXPECT_FALSE(BarResolved) << "\"Bar\" should not be resolved yet";
419   EXPECT_FALSE(BazResolved) << "\"Baz\" should not be resolved yet";
420 
421   // Resolve the symbols (but do not emit them).
422   FooR->resolve({{Foo, FooSym}});
423   BarR->resolve({{Bar, BarSym}});
424   BazR->resolve({{Baz, BazSym}});
425 
426   // Verify that the symbols have been resolved, but are not ready yet.
427   EXPECT_TRUE(FooResolved) << "\"Foo\" should be resolved now";
428   EXPECT_TRUE(BarResolved) << "\"Bar\" should be resolved now";
429   EXPECT_TRUE(BazResolved) << "\"Baz\" should be resolved now";
430 
431   EXPECT_FALSE(FooReady) << "\"Foo\" should not be ready yet";
432   EXPECT_FALSE(BarReady) << "\"Bar\" should not be ready yet";
433   EXPECT_FALSE(BazReady) << "\"Baz\" should not be ready yet";
434 
435   // Emit two of the symbols.
436   FooR->emit();
437   BarR->emit();
438 
439   // Verify that nothing is ready until the circular dependence is resolved.
440   EXPECT_FALSE(FooReady) << "\"Foo\" still should not be ready";
441   EXPECT_FALSE(BarReady) << "\"Bar\" still should not be ready";
442   EXPECT_FALSE(BazReady) << "\"Baz\" still should not be ready";
443 
444   // Emit the last symbol.
445   BazR->emit();
446 
447   // Verify that everything becomes ready once the circular dependence resolved.
448   EXPECT_TRUE(FooReady) << "\"Foo\" should be ready now";
449   EXPECT_TRUE(BarReady) << "\"Bar\" should be ready now";
450   EXPECT_TRUE(BazReady) << "\"Baz\" should be ready now";
451 }
452 
453 TEST_F(CoreAPIsStandardTest, DropMaterializerWhenEmpty) {
454   bool DestructorRun = false;
455 
456   JITSymbolFlags WeakExported(JITSymbolFlags::Exported);
457   WeakExported |= JITSymbolFlags::Weak;
458 
459   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
460       SymbolFlagsMap({{Foo, WeakExported}, {Bar, WeakExported}}),
461       [](MaterializationResponsibility R) {
462         llvm_unreachable("Unexpected call to materialize");
463       },
464       [&](const JITDylib &JD, SymbolStringPtr Name) {
465         EXPECT_TRUE(Name == Foo || Name == Bar)
466             << "Discard of unexpected symbol?";
467       },
468       [&]() { DestructorRun = true; });
469 
470   cantFail(JD.define(MU));
471 
472   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
473 
474   EXPECT_FALSE(DestructorRun)
475       << "MaterializationUnit should not have been destroyed yet";
476 
477   cantFail(JD.define(absoluteSymbols({{Bar, BarSym}})));
478 
479   EXPECT_TRUE(DestructorRun)
480       << "MaterializationUnit should have been destroyed";
481 }
482 
483 TEST_F(CoreAPIsStandardTest, AddAndMaterializeLazySymbol) {
484   bool FooMaterialized = false;
485   bool BarDiscarded = false;
486 
487   JITSymbolFlags WeakExported(JITSymbolFlags::Exported);
488   WeakExported |= JITSymbolFlags::Weak;
489 
490   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
491       SymbolFlagsMap({{Foo, JITSymbolFlags::Exported}, {Bar, WeakExported}}),
492       [&](MaterializationResponsibility R) {
493         assert(BarDiscarded && "Bar should have been discarded by this point");
494         R.resolve(SymbolMap({{Foo, FooSym}}));
495         R.emit();
496         FooMaterialized = true;
497       },
498       [&](const JITDylib &JD, SymbolStringPtr Name) {
499         EXPECT_EQ(Name, Bar) << "Expected Name to be Bar";
500         BarDiscarded = true;
501       });
502 
503   cantFail(JD.define(MU));
504   cantFail(JD.define(absoluteSymbols({{Bar, BarSym}})));
505 
506   SymbolNameSet Names({Foo});
507 
508   bool OnResolutionRun = false;
509   bool OnReadyRun = false;
510 
511   auto OnResolution = [&](Expected<SymbolMap> Result) {
512     EXPECT_TRUE(!!Result) << "Resolution unexpectedly returned error";
513     auto I = Result->find(Foo);
514     EXPECT_NE(I, Result->end()) << "Could not find symbol definition";
515     EXPECT_EQ(I->second.getAddress(), FooSym.getAddress())
516         << "Resolution returned incorrect result";
517     OnResolutionRun = true;
518   };
519 
520   auto OnReady = [&](Error Err) {
521     cantFail(std::move(Err));
522     OnReadyRun = true;
523   };
524 
525   ES.lookup({&JD}, Names, std::move(OnResolution), std::move(OnReady),
526             NoDependenciesToRegister);
527 
528   EXPECT_TRUE(FooMaterialized) << "Foo was not materialized";
529   EXPECT_TRUE(BarDiscarded) << "Bar was not discarded";
530   EXPECT_TRUE(OnResolutionRun) << "OnResolutionCallback was not run";
531   EXPECT_TRUE(OnReadyRun) << "OnReady was not run";
532 }
533 
534 TEST_F(CoreAPIsStandardTest, DefineMaterializingSymbol) {
535   bool ExpectNoMoreMaterialization = false;
536   ES.setDispatchMaterialization(
537       [&](JITDylib &JD, std::unique_ptr<MaterializationUnit> MU) {
538         if (ExpectNoMoreMaterialization)
539           ADD_FAILURE() << "Unexpected materialization";
540         MU->doMaterialize(JD);
541       });
542 
543   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
544       SymbolFlagsMap({{Foo, FooSym.getFlags()}}),
545       [&](MaterializationResponsibility R) {
546         cantFail(
547             R.defineMaterializing(SymbolFlagsMap({{Bar, BarSym.getFlags()}})));
548         R.resolve(SymbolMap({{Foo, FooSym}, {Bar, BarSym}}));
549         R.emit();
550       });
551 
552   cantFail(JD.define(MU));
553   cantFail(lookup({&JD}, Foo));
554 
555   // Assert that materialization is complete by now.
556   ExpectNoMoreMaterialization = true;
557 
558   // Look up bar to verify that no further materialization happens.
559   auto BarResult = cantFail(lookup({&JD}, Bar));
560   EXPECT_EQ(BarResult.getAddress(), BarSym.getAddress())
561       << "Expected Bar == BarSym";
562 }
563 
564 TEST_F(CoreAPIsStandardTest, FallbackDefinitionGeneratorTest) {
565   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
566 
567   JD.setFallbackDefinitionGenerator(
568       [&](JITDylib &JD2, const SymbolNameSet &Names) {
569         cantFail(JD2.define(absoluteSymbols({{Bar, BarSym}})));
570         return SymbolNameSet({Bar});
571       });
572 
573   auto Result = cantFail(lookup({&JD}, {Foo, Bar}));
574 
575   EXPECT_EQ(Result.count(Bar), 1U) << "Expected to find fallback def for 'bar'";
576   EXPECT_EQ(Result[Bar].getAddress(), BarSym.getAddress())
577       << "Expected fallback def for Bar to be equal to BarSym";
578 }
579 
580 TEST_F(CoreAPIsStandardTest, FailResolution) {
581   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
582       SymbolFlagsMap(
583           {{Foo, JITSymbolFlags::Weak}, {Bar, JITSymbolFlags::Weak}}),
584       [&](MaterializationResponsibility R) { R.failMaterialization(); });
585 
586   cantFail(JD.define(MU));
587 
588   SymbolNameSet Names({Foo, Bar});
589   auto Result = lookup({&JD}, Names);
590 
591   EXPECT_FALSE(!!Result) << "Expected failure";
592   if (!Result) {
593     handleAllErrors(Result.takeError(),
594                     [&](FailedToMaterialize &F) {
595                       EXPECT_EQ(F.getSymbols(), Names)
596                           << "Expected to fail on symbols in Names";
597                     },
598                     [](ErrorInfoBase &EIB) {
599                       std::string ErrMsg;
600                       {
601                         raw_string_ostream ErrOut(ErrMsg);
602                         EIB.log(ErrOut);
603                       }
604                       ADD_FAILURE()
605                           << "Expected a FailedToResolve error. Got:\n"
606                           << ErrMsg;
607                     });
608   }
609 }
610 
611 TEST_F(CoreAPIsStandardTest, TestLookupWithUnthreadedMaterialization) {
612   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
613       SymbolFlagsMap({{Foo, JITSymbolFlags::Exported}}),
614       [&](MaterializationResponsibility R) {
615         R.resolve({{Foo, FooSym}});
616         R.emit();
617       });
618 
619   cantFail(JD.define(MU));
620 
621   auto FooLookupResult = cantFail(lookup({&JD}, Foo));
622 
623   EXPECT_EQ(FooLookupResult.getAddress(), FooSym.getAddress())
624       << "lookup returned an incorrect address";
625   EXPECT_EQ(FooLookupResult.getFlags(), FooSym.getFlags())
626       << "lookup returned incorrect flags";
627 }
628 
629 TEST_F(CoreAPIsStandardTest, TestLookupWithThreadedMaterialization) {
630 #if LLVM_ENABLE_THREADS
631 
632   std::thread MaterializationThread;
633   ES.setDispatchMaterialization(
634       [&](JITDylib &JD, std::unique_ptr<MaterializationUnit> MU) {
635         auto SharedMU = std::shared_ptr<MaterializationUnit>(std::move(MU));
636         MaterializationThread =
637             std::thread([SharedMU, &JD]() { SharedMU->doMaterialize(JD); });
638       });
639 
640   cantFail(JD.define(absoluteSymbols({{Foo, FooSym}})));
641 
642   auto FooLookupResult = cantFail(lookup({&JD}, Foo));
643 
644   EXPECT_EQ(FooLookupResult.getAddress(), FooSym.getAddress())
645       << "lookup returned an incorrect address";
646   EXPECT_EQ(FooLookupResult.getFlags(), FooSym.getFlags())
647       << "lookup returned incorrect flags";
648   MaterializationThread.join();
649 #endif
650 }
651 
652 TEST_F(CoreAPIsStandardTest, TestGetRequestedSymbolsAndReplace) {
653   // Test that GetRequestedSymbols returns the set of symbols that currently
654   // have pending queries, and test that MaterializationResponsibility's
655   // replace method can be used to return definitions to the JITDylib in a new
656   // MaterializationUnit.
657   SymbolNameSet Names({Foo, Bar});
658 
659   bool FooMaterialized = false;
660   bool BarMaterialized = false;
661 
662   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
663       SymbolFlagsMap({{Foo, FooSym.getFlags()}, {Bar, BarSym.getFlags()}}),
664       [&](MaterializationResponsibility R) {
665         auto Requested = R.getRequestedSymbols();
666         EXPECT_EQ(Requested.size(), 1U) << "Expected one symbol requested";
667         EXPECT_EQ(*Requested.begin(), Foo) << "Expected \"Foo\" requested";
668 
669         auto NewMU = llvm::make_unique<SimpleMaterializationUnit>(
670             SymbolFlagsMap({{Bar, BarSym.getFlags()}}),
671             [&](MaterializationResponsibility R2) {
672               R2.resolve(SymbolMap({{Bar, BarSym}}));
673               R2.emit();
674               BarMaterialized = true;
675             });
676 
677         R.replace(std::move(NewMU));
678 
679         R.resolve(SymbolMap({{Foo, FooSym}}));
680         R.emit();
681 
682         FooMaterialized = true;
683       });
684 
685   cantFail(JD.define(MU));
686 
687   EXPECT_FALSE(FooMaterialized) << "Foo should not be materialized yet";
688   EXPECT_FALSE(BarMaterialized) << "Bar should not be materialized yet";
689 
690   auto FooSymResult = cantFail(lookup({&JD}, Foo));
691   EXPECT_EQ(FooSymResult.getAddress(), FooSym.getAddress())
692       << "Address mismatch for Foo";
693 
694   EXPECT_TRUE(FooMaterialized) << "Foo should be materialized now";
695   EXPECT_FALSE(BarMaterialized) << "Bar still should not be materialized";
696 
697   auto BarSymResult = cantFail(lookup({&JD}, Bar));
698   EXPECT_EQ(BarSymResult.getAddress(), BarSym.getAddress())
699       << "Address mismatch for Bar";
700   EXPECT_TRUE(BarMaterialized) << "Bar should be materialized now";
701 }
702 
703 TEST_F(CoreAPIsStandardTest, TestMaterializationResponsibilityDelegation) {
704   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
705       SymbolFlagsMap({{Foo, FooSym.getFlags()}, {Bar, BarSym.getFlags()}}),
706       [&](MaterializationResponsibility R) {
707         auto R2 = R.delegate({Bar});
708 
709         R.resolve({{Foo, FooSym}});
710         R.emit();
711         R2.resolve({{Bar, BarSym}});
712         R2.emit();
713       });
714 
715   cantFail(JD.define(MU));
716 
717   auto Result = lookup({&JD}, {Foo, Bar});
718 
719   EXPECT_TRUE(!!Result) << "Result should be a success value";
720   EXPECT_EQ(Result->count(Foo), 1U) << "\"Foo\" entry missing";
721   EXPECT_EQ(Result->count(Bar), 1U) << "\"Bar\" entry missing";
722   EXPECT_EQ((*Result)[Foo].getAddress(), FooSym.getAddress())
723       << "Address mismatch for \"Foo\"";
724   EXPECT_EQ((*Result)[Bar].getAddress(), BarSym.getAddress())
725       << "Address mismatch for \"Bar\"";
726 }
727 
728 TEST_F(CoreAPIsStandardTest, TestMaterializeWeakSymbol) {
729   // Confirm that once a weak definition is selected for materialization it is
730   // treated as strong.
731   JITSymbolFlags WeakExported = JITSymbolFlags::Exported;
732   WeakExported &= JITSymbolFlags::Weak;
733 
734   std::unique_ptr<MaterializationResponsibility> FooResponsibility;
735   auto MU = llvm::make_unique<SimpleMaterializationUnit>(
736       SymbolFlagsMap({{Foo, FooSym.getFlags()}}),
737       [&](MaterializationResponsibility R) {
738         FooResponsibility =
739             llvm::make_unique<MaterializationResponsibility>(std::move(R));
740       });
741 
742   cantFail(JD.define(MU));
743   auto OnResolution = [](Expected<SymbolMap> Result) {
744     cantFail(std::move(Result));
745   };
746 
747   auto OnReady = [](Error Err) { cantFail(std::move(Err)); };
748 
749   ES.lookup({&JD}, {Foo}, std::move(OnResolution), std::move(OnReady),
750             NoDependenciesToRegister);
751 
752   auto MU2 = llvm::make_unique<SimpleMaterializationUnit>(
753       SymbolFlagsMap({{Foo, JITSymbolFlags::Exported}}),
754       [](MaterializationResponsibility R) {
755         llvm_unreachable("This unit should never be materialized");
756       });
757 
758   auto Err = JD.define(MU2);
759   EXPECT_TRUE(!!Err) << "Expected failure value";
760   EXPECT_TRUE(Err.isA<DuplicateDefinition>())
761       << "Expected a duplicate definition error";
762   consumeError(std::move(Err));
763 
764   FooResponsibility->resolve(SymbolMap({{Foo, FooSym}}));
765   FooResponsibility->emit();
766 }
767 
768 } // namespace
769