llvm.org GIT mirror llvm / d912be9
Change linkInModule to take a std::unique_ptr. Passing in a std::unique_ptr should help find errors when the module is used after being linked into another module. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@255842 91177308-0d34-0410-b5e6-96231b3b80d8 Rafael Espindola 4 years ago
15 changed file(s) with 136 addition(s) and 66 deletion(s). Raw diff Collapse all Expand all
2020 import "errors"
2121
2222 func LinkModules(Dest, Src Module) error {
23 var cmsg *C.char
24 failed := C.LLVMLinkModules(Dest.C, Src.C, C.LLVMLinkerDestroySource, &cmsg)
23 failed := C.LLVMLinkModules2(Dest.C, Src.C)
2524 if failed != 0 {
26 err := errors.New(C.GoString(cmsg))
27 C.LLVMDisposeMessage(cmsg)
25 err := errors.New("Linking failed")
2826 return err
2927 }
3028 return nil
2424
2525 /* llmodule -> llmodule -> unit */
2626 CAMLprim value llvm_link_modules(LLVMModuleRef Dst, LLVMModuleRef Src) {
27 char* Message;
28
29 if (LLVMLinkModules(Dst, Src, 0, &Message))
30 llvm_raise(*caml_named_value("Llvm_linker.Error"), Message);
27 if (LLVMLinkModules2(Dst, Src))
28 llvm_raise(*caml_named_value("Llvm_linker.Error"), "Linking failed");
3129
3230 return Val_unit;
3331 }
1010
1111 let () = Callback.register_exception "Llvm_linker.Error" (Error "")
1212
13 external link_modules : Llvm.llmodule -> Llvm.llmodule -> unit
14 = "llvm_link_modules"
13 external link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit
14 = "llvm_link_modules"
1313
1414 exception Error of string
1515
16 (** [link_modules dst src mode] links [src] into [dst], raising [Error]
17 if the linking fails. *)
18 val link_modules : Llvm.llmodule -> Llvm.llmodule -> unit
16 (** [link_modules' dst src] links [src] into [dst], raising [Error]
17 if the linking fails. The src module is destroyed. *)
18 val link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit
4040 in the 3.9 release. Please migrate to using CMake. For more information see:
4141 `Building LLVM with CMake `_
4242
43 * The C API function LLVMLinkModules is deprecated. It will be removed in the
44 3.9 release. Please migrate to LLVMLinkModules2. Unlike the old function the
45 new one
46
47 * Doesn't take an unused parameter.
48 * Destroys the source instead of only damaging it.
49 * Does not record a message. Use the diagnostic handler instead.
50
4351 .. NOTE
4452 For small 1-3 sentence descriptions, just add an entry at the end of
4553 this list. If your description won't fit comfortably in one bullet
8290
8391 During this release ...
8492
93 * The ocaml function link_modules has been replaced with link_modules' which
94 uses LLVMLinkModules2.
95
8596
8697 External Open Source Projects Using LLVM 3.8
8798 ============================================
3434
3535 Linker(Module &M);
3636
37 /// \brief Link \p Src into the composite. The source is destroyed.
37 /// \brief Link \p Src into the composite.
3838 ///
3939 /// Passing OverrideSymbols as true will have symbols from Src
4040 /// shadow those in the Dest.
4343 /// are part of the set will be imported from the source module.
4444 ///
4545 /// Returns true on error.
46 bool linkInModule(Module &Src, unsigned Flags = Flags::None,
46 bool linkInModule(std::unique_ptr Src, unsigned Flags = Flags::None,
4747 const FunctionInfoIndex *Index = nullptr,
4848 DenseSet *FunctionsToImport = nullptr);
4949
50 static bool linkModules(Module &Dest, Module &Src,
50 /// This exists to implement the deprecated LLVMLinkModules C api. Don't use
51 /// for anything else.
52 bool linkInModuleForCAPI(Module &Src);
53
54 static bool linkModules(Module &Dest, std::unique_ptr Src,
5155 unsigned Flags = Flags::None);
52
5356 };
5457
5558 /// Create a new module with exported local functions renamed and promoted
5659 /// for ThinLTO.
57 std::unique_ptr renameModuleForThinLTO(std::unique_ptr &M,
60 std::unique_ptr renameModuleForThinLTO(std::unique_ptr M,
5861 const FunctionInfoIndex *Index);
5962
6063 } // End llvm namespace
2626 should not be used. */
2727 } LLVMLinkerMode;
2828
29 /* Links the source module into the destination module, taking ownership
30 * of the source module away from the caller. Optionally returns a
31 * human-readable description of any errors that occurred in linking.
32 * OutMessage must be disposed with LLVMDisposeMessage. The return value
33 * is true if an error occurred, false otherwise.
29 /* Links the source module into the destination module. The source module is
30 * damaged. The only thing that can be done is destroy it. Optionally returns a
31 * human-readable description of any errors that occurred in linking. OutMessage
32 * must be disposed with LLVMDisposeMessage. The return value is true if an
33 * error occurred, false otherwise.
3434 *
3535 * Note that the linker mode parameter \p Unused is no longer used, and has
36 * no effect. */
36 * no effect.
37 *
38 * This function is deprecated. Use LLVMLinkModules2 instead.
39 */
3740 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
3841 LLVMLinkerMode Unused, char **OutMessage);
42
43 /* Links the source module into the destination module. The source module is
44 * destroyed.
45 * The return value is true if an error occurred, false otherwise.
46 * Use the diagnostic handler to get any diagnostic message.
47 */
48 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src);
3949
4050 #ifdef __cplusplus
4151 }
105105 assert(&Mod->getModule().getContext() == &Context &&
106106 "Expected module in same context");
107107
108 bool ret = IRLinker->linkInModule(Mod->getModule());
108 bool ret = IRLinker->linkInModule(Mod->takeModule());
109109
110110 const std::vector &undefs = Mod->getAsmUndefinedRefs();
111111 for (int i = 0, e = undefs.size(); i != e; ++i)
788788
789789 Linker::Linker(Module &M) : Mover(M) {}
790790
791 bool Linker::linkInModule(Module &Src, unsigned Flags,
791 bool Linker::linkInModule(std::unique_ptr Src, unsigned Flags,
792792 const FunctionInfoIndex *Index,
793793 DenseSet *FunctionsToImport) {
794 ModuleLinker TheLinker(Mover, Src, Flags, Index, FunctionsToImport);
794 ModuleLinker TheLinker(Mover, *Src, Flags, Index, FunctionsToImport);
795 return TheLinker.run();
796 }
797
798 bool Linker::linkInModuleForCAPI(Module &Src) {
799 ModuleLinker TheLinker(Mover, Src, 0, nullptr, nullptr);
795800 return TheLinker.run();
796801 }
797802
804809 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
805810 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
806811 /// relied on to be consistent.
807 bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
812 bool Linker::linkModules(Module &Dest, std::unique_ptr Src,
813 unsigned Flags) {
808814 Linker L(Dest);
809 return L.linkInModule(Src, Flags);
815 return L.linkInModule(std::move(Src), Flags);
810816 }
811817
812818 std::unique_ptr
813 llvm::renameModuleForThinLTO(std::unique_ptr &M,
819 llvm::renameModuleForThinLTO(std::unique_ptr M,
814820 const FunctionInfoIndex *Index) {
815821 std::unique_ptr RenamedModule(
816822 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
817823 Linker L(*RenamedModule.get());
818 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
824 if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
819825 return nullptr;
820826 return RenamedModule;
821827 }
842848 std::string Message;
843849 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
844850
845 LLVMBool Result = Linker::linkModules(*D, *unwrap(Src));
851 Linker L(*D);
852 Module *M = unwrap(Src);
853 LLVMBool Result = L.linkInModuleForCAPI(*M);
846854
847855 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
848856
850858 *OutMessages = strdup(Message.c_str());
851859 return Result;
852860 }
861
862 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
863 Module *D = unwrap(Dest);
864 std::unique_ptr M(unwrap(Src));
865 return Linker::linkModules(*D, std::move(M));
866 }
7070
7171 /// Retrieve a Module from the cache or lazily load it on demand.
7272 Module &operator()(StringRef FileName);
73
74 std::unique_ptr takeModule(StringRef FileName) {
75 auto I = ModuleMap.find(FileName);
76 assert(I != ModuleMap.end());
77 std::unique_ptr Ret = std::move(I->second);
78 ModuleMap.erase(I);
79 return Ret;
80 }
7381 };
7482
7583 // Get a Module for \p FileName from the cache, or load it lazily.
148156 //
149157 // \p ModuleToFunctionsToImportMap is filled with the set of Function to import
150158 // per Module.
151 static void GetImportList(
152 Module &DestModule, SmallVector &Worklist,
153 StringSet<> &CalledFunctions,
154 std::map>> &
155 ModuleToFunctionsToImportMap,
156 const FunctionInfoIndex &Index, ModuleLazyLoaderCache &ModuleLoaderCache) {
159 static void GetImportList(Module &DestModule,
160 SmallVector &Worklist,
161 StringSet<> &CalledFunctions,
162 std::map>
163 &ModuleToFunctionsToImportMap,
164 const FunctionInfoIndex &Index,
165 ModuleLazyLoaderCache &ModuleLoaderCache) {
157166 while (!Worklist.empty()) {
158167 auto CalledFunctionName = Worklist.pop_back_val();
159168 DEBUG(dbgs() << DestModule.getModuleIdentifier() << ": Process import for "
237246
238247 // Add the function to the import list
239248 auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
240 Entry.first = &SrcModule;
241 Entry.second.insert(F);
249 Entry.insert(F);
242250
243251 // Process the newly imported functions and add callees to the worklist.
244252 F->materialize();
273281 Linker TheLinker(DestModule);
274282
275283 // Map of Module -> List of Function to import from the Module
276 std::mapstd::pair>>
284 std::mapDenseSet>>
277285 ModuleToFunctionsToImportMap;
278286
279287 // Analyze the summaries and get the list of functions to import by
286294 // Do the actual import of functions now, one Module at a time
287295 for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
288296 // Get the module for the import
289 auto &FunctionsToImport = FunctionsToImportPerModule.second.second;
290 auto *SrcModule = FunctionsToImportPerModule.second.first;
297 auto &FunctionsToImport = FunctionsToImportPerModule.second;
298 std::unique_ptr SrcModule =
299 ModuleLoaderCache.takeModule(FunctionsToImportPerModule.first);
291300 assert(&DestModule.getContext() == &SrcModule->getContext() &&
292301 "Context mismatch");
293302
294303 // Link in the specified functions.
295 if (TheLinker.linkInModule(*SrcModule, Linker::Flags::None, &Index,
296 &FunctionsToImport))
304 if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
305 &Index, &FunctionsToImport))
297306 report_fatal_error("Function Import: link error");
298307
299308 ImportedCount += FunctionsToImport.size();
3838
3939 let m1 = make_module "one"
4040 and m2 = make_module "two" in
41 link_modules m1 m2;
41 link_modules' m1 m2;
4242 dispose_module m1;
43 dispose_module m2;
4443
4544 let m1 = make_module "one"
4645 and m2 = make_module "two" in
47 link_modules m1 m2;
46 link_modules' m1 m2;
4847 dispose_module m1;
4948
5049 let m1 = make_module "one"
5150 and m2 = make_module "one" in
5251 try
53 link_modules m1 m2;
52 link_modules' m1 m2;
5453 failwith "must raise"
5554 with Error _ ->
56 dispose_module m1;
57 dispose_module m2
55 dispose_module m1
5856
5957 (*===-- Driver ------------------------------------------------------------===*)
6058
131131 if (!M.get()) return true;
132132
133133 outs() << "Linking in input file: '" << Filenames[i] << "'\n";
134 if (Linker::linkModules(*Program, *M))
134 if (Linker::linkModules(*Program, std::move(M)))
135135 return true;
136136 }
137137
220220 std::unique_ptr M2,
221221 std::string &Error,
222222 bool &Broken) {
223 if (Linker::linkModules(*M1, *M2))
223 if (Linker::linkModules(*M1, std::move(M2)))
224224 exit(1);
225225
226226 // Execute the program.
386386 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
387387 }
388388
389 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
389 if (Linker::linkModules(*ToNotOptimize,
390 std::move(ToOptimizeLoopExtracted)))
390391 exit(1);
391392
392393 MiscompiledFunctions.clear();
413414 // extraction both didn't break the program, and didn't mask the problem.
414415 // Replace the current program with the loop extracted version, and try to
415416 // extract another loop.
416 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
417 if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
417418 exit(1);
418419
419420 // All of the Function*'s in the MiscompiledFunctions list are in the old
581582 if (!I->isDeclaration())
582583 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
583584
584 if (Linker::linkModules(*ProgClone, *Extracted))
585 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
585586 exit(1);
586587
587588 // Set the new program and delete the old one.
203203 // Link in the specified function.
204204 DenseSet FunctionsToImport;
205205 FunctionsToImport.insert(F);
206 if (L.linkInModule(*M, Linker::Flags::None, Index.get(),
206 if (L.linkInModule(std::move(M), Linker::Flags::None, Index.get(),
207207 &FunctionsToImport))
208208 return false;
209209 }
244244 if (Verbose)
245245 errs() << "Linking in '" << File << "'\n";
246246
247 if (L.linkInModule(*M, ApplicableFlags, Index.get()))
247 if (L.linkInModule(std::move(M), ApplicableFlags, Index.get()))
248248 return false;
249249 // All linker flags apply to linking of subsequent files.
250250 ApplicableFlags = Flags;
9797
9898 Module *LinkedModule = new Module("MyModuleLinked", Ctx);
9999 Ctx.setDiagnosticHandler(expectNoDiags);
100 Linker::linkModules(*LinkedModule, *M);
101
102 // Delete the original module.
103 M.reset();
100 Linker::linkModules(*LinkedModule, std::move(M));
104101
105102 // Check that the global "@switch.bas" is well-formed.
106103 const GlobalVariable *LinkedGV = LinkedModule->getNamedGlobal("switch.bas");
174171 std::unique_ptr InternalM(getInternal(Ctx));
175172 std::unique_ptr EmptyM(new Module("EmptyModule1", Ctx));
176173 Ctx.setDiagnosticHandler(expectNoDiags);
177 Linker::linkModules(*EmptyM, *InternalM);
174 Linker::linkModules(*EmptyM, std::move(InternalM));
178175 }
179176
180177 TEST_F(LinkModuleTest, EmptyModule2) {
181178 std::unique_ptr InternalM(getInternal(Ctx));
182179 std::unique_ptr EmptyM(new Module("EmptyModule1", Ctx));
183180 Ctx.setDiagnosticHandler(expectNoDiags);
184 Linker::linkModules(*InternalM, *EmptyM);
181 Linker::linkModules(*InternalM, std::move(EmptyM));
185182 }
186183
187184 TEST_F(LinkModuleTest, TypeMerge) {
197194 std::unique_ptr M2 = parseAssemblyString(M2Str, Err, C);
198195
199196 Ctx.setDiagnosticHandler(expectNoDiags);
200 Linker::linkModules(*M1, *M2);
197 Linker::linkModules(*M1, std::move(M2));
201198
202199 EXPECT_EQ(M1->getNamedGlobal("t1")->getType(),
203200 M1->getNamedGlobal("t2")->getType());
225222 EXPECT_EQ(1, result);
226223 EXPECT_STREQ("Linking globals named 'foo': symbol multiply defined!", errout);
227224 LLVMDisposeMessage(errout);
225 }
226
227 TEST_F(LinkModuleTest, NewCAPISuccess) {
228 std::unique_ptr DestM(getExternal(Ctx, "foo"));
229 std::unique_ptr SourceM(getExternal(Ctx, "bar"));
230 LLVMBool Result =
231 LLVMLinkModules2(wrap(DestM.get()), wrap(SourceM.release()));
232 EXPECT_EQ(0, Result);
233 // "bar" is present in destination module
234 EXPECT_NE(nullptr, DestM->getFunction("bar"));
235 }
236
237 static void diagnosticHandler(LLVMDiagnosticInfoRef DI, void *C) {
238 auto *Err = reinterpret_cast(C);
239 char *CErr = LLVMGetDiagInfoDescription(DI);
240 *Err = CErr;
241 LLVMDisposeMessage(CErr);
242 }
243
244 TEST_F(LinkModuleTest, NewCAPIFailure) {
245 // Symbol clash between two modules
246 LLVMContext Ctx;
247 std::string Err;
248 LLVMContextSetDiagnosticHandler(wrap(&Ctx), diagnosticHandler, &Err);
249
250 std::unique_ptr DestM(getExternal(Ctx, "foo"));
251 std::unique_ptr SourceM(getExternal(Ctx, "foo"));
252 LLVMBool Result =
253 LLVMLinkModules2(wrap(DestM.get()), wrap(SourceM.release()));
254 EXPECT_EQ(1, Result);
255 EXPECT_EQ("Linking globals named 'foo': symbol multiply defined!", Err);
228256 }
229257
230258 TEST_F(LinkModuleTest, MoveDistinctMDs) {
275303 auto Dst = llvm::make_unique("Linked", C);
276304 ASSERT_TRUE(Dst.get());
277305 Ctx.setDiagnosticHandler(expectNoDiags);
278 Linker::linkModules(*Dst, *Src);
306 Linker::linkModules(*Dst, std::move(Src));
279307
280308 // Check that distinct metadata was moved, not cloned. Even !4, the uniqued
281309 // node, should effectively be moved, since its only operand hasn't changed.