llvm.org GIT mirror llvm / f0356fe
Kill ModuleProvider and ghost linkage by inverting the relationship between Modules and ModuleProviders. Because the "ModuleProvider" simply materializes GlobalValues now, and doesn't provide modules, it's renamed to "GVMaterializer". Code that used to need a ModuleProvider to materialize Functions can now materialize the Functions directly. Functions no longer use a magic linkage to record that they're materializable; they simply ask the GVMaterializer. Because the C ABI must never change, we can't remove LLVMModuleProviderRef or the functions that refer to it. Instead, because Module now exposes the same functionality ModuleProvider used to, we store a Module* in any LLVMModuleProviderRef and translate in the wrapper methods. The bindings to other languages still use the ModuleProvider concept. It would probably be worth some time to update them to follow the C++ more closely, but I don't intend to do it. Fixes http://llvm.org/PR5737 and http://llvm.org/PR5735. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@94686 91177308-0d34-0410-b5e6-96231b3b80d8 Jeffrey Yasskin 9 years ago
62 changed file(s) with 660 addition(s) and 756 deletion(s). Raw diff Collapse all Expand all
170170
171171
172172

                  
                
173 ExistingModuleProvider *OurModuleProvider =
174 new ExistingModuleProvider(TheModule);
175
176 FunctionPassManager OurFPM(OurModuleProvider);
173 FunctionPassManager OurFPM(TheModule);
177174
178175 // Set up the optimizer pipeline. Start with registering info about how the
179176 // target lays out data structures.
197194
198195
199196
200

This code defines two objects, an ExistingModuleProvider and a

201 FunctionPassManager. The former is basically a wrapper around our
202 Module that the PassManager requires. It provides certain flexibility
203 that we're not going to take advantage of here, so I won't dive into any details
204 about it.

205
206

The meat of the matter here, is the definition of "OurFPM". It

207 requires a pointer to the Module (through the ModuleProvider)
208 to construct itself. Once it is set up, we use a series of "add" calls to add
209 a bunch of LLVM passes. The first pass is basically boilerplate, it adds a pass
210 so that later optimizations know how the data structures in the program are
211 laid out. The "TheExecutionEngine" variable is related to the JIT,
212 which we will get to in the next section.

197

This code defines a FunctionPassManager, "OurFPM". It

198 requires a pointer to the Module to construct itself. Once it is set
199 up, we use a series of "add" calls to add a bunch of LLVM passes. The first
200 pass is basically boilerplate, it adds a pass so that later optimizations know
201 how the data structures in the program are laid out. The
202 "TheExecutionEngine" variable is related to the JIT, which we will get
203 to in the next section.

213204
214205

In this case, we choose to add 4 optimization passes. The passes we chose

215206 here are a pretty standard set of "cleanup" optimizations that are useful for
301292 ...
302293 int main() {
303294 ..
304 // Create the JIT. This takes ownership of the module and module provider.
305 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
295 // Create the JIT. This takes ownership of the module.
296 TheExecutionEngine = EngineBuilder(TheModule).create();
306297 ..
307298 }
308299
514505 #include "llvm/ExecutionEngine/JIT.h"
515506 #include "llvm/LLVMContext.h"
516507 #include "llvm/Module.h"
517 #include "llvm/ModuleProvider.h"
518508 #include "llvm/PassManager.h"
519509 #include "llvm/Analysis/Verifier.h"
520510 #include "llvm/Target/TargetData.h"
10831073 // Make the module, which holds all the code.
10841074 TheModule = new Module("my cool jit", Context);
10851075
1086 ExistingModuleProvider *OurModuleProvider =
1087 new ExistingModuleProvider(TheModule);
1088
1089 // Create the JIT. This takes ownership of the module and module provider.
1090 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
1091
1092 FunctionPassManager OurFPM(OurModuleProvider);
1076 // Create the JIT. This takes ownership of the module.
1077 TheExecutionEngine = EngineBuilder(TheModule).create();
1078
1079 FunctionPassManager OurFPM(TheModule);
10931080
10941081 // Set up the optimizer pipeline. Start with registering info about how the
10951082 // target lays out data structures.
905905 #include "llvm/ExecutionEngine/JIT.h"
906906 #include "llvm/LLVMContext.h"
907907 #include "llvm/Module.h"
908 #include "llvm/ModuleProvider.h"
909908 #include "llvm/PassManager.h"
910909 #include "llvm/Analysis/Verifier.h"
911910 #include "llvm/Target/TargetData.h"
17191718 // Make the module, which holds all the code.
17201719 TheModule = new Module("my cool jit", Context);
17211720
1722 ExistingModuleProvider *OurModuleProvider =
1723 new ExistingModuleProvider(TheModule);
1724
1725 // Create the JIT. This takes ownership of the module and module provider.
1726 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
1727
1728 FunctionPassManager OurFPM(OurModuleProvider);
1721 // Create the JIT. This takes ownership of the module.
1722 TheExecutionEngine = EngineBuilder(TheModule).create();
1723
1724 FunctionPassManager OurFPM(TheModule);
17291725
17301726 // Set up the optimizer pipeline. Start with registering info about how the
17311727 // target lays out data structures.
824824 #include "llvm/ExecutionEngine/JIT.h"
825825 #include "llvm/LLVMContext.h"
826826 #include "llvm/Module.h"
827 #include "llvm/ModuleProvider.h"
828827 #include "llvm/PassManager.h"
829828 #include "llvm/Analysis/Verifier.h"
830829 #include "llvm/Target/TargetData.h"
17561755 // Make the module, which holds all the code.
17571756 TheModule = new Module("my cool jit", Context);
17581757
1759 ExistingModuleProvider *OurModuleProvider =
1760 new ExistingModuleProvider(TheModule);
1761
1762 // Create the JIT. This takes ownership of the module and module provider.
1763 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
1764
1765 FunctionPassManager OurFPM(OurModuleProvider);
1758 // Create the JIT. This takes ownership of the module.
1759 TheExecutionEngine = EngineBuilder(TheModule).create();
1760
1761 FunctionPassManager OurFPM(TheModule);
17661762
17671763 // Set up the optimizer pipeline. Start with registering info about how the
17681764 // target lays out data structures.
10071007 #include "llvm/ExecutionEngine/JIT.h"
10081008 #include "llvm/LLVMContext.h"
10091009 #include "llvm/Module.h"
1010 #include "llvm/ModuleProvider.h"
10111010 #include "llvm/PassManager.h"
10121011 #include "llvm/Analysis/Verifier.h"
10131012 #include "llvm/Target/TargetData.h"
21042103 // Make the module, which holds all the code.
21052104 TheModule = new Module("my cool jit", Context);
21062105
2107 ExistingModuleProvider *OurModuleProvider =
2108 new ExistingModuleProvider(TheModule);
2109
2110 // Create the JIT. This takes ownership of the module and module provider.
2111 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
2112
2113 FunctionPassManager OurFPM(OurModuleProvider);
2106 // Create the JIT. This takes ownership of the module.
2107 TheExecutionEngine = EngineBuilder(TheModule).create();
2108
2109 FunctionPassManager OurFPM(TheModule);
21142110
21152111 // Set up the optimizer pipeline. Start with registering info about how the
21162112 // target lays out data structures.
2626
2727 #include "BrainF.h"
2828 #include "llvm/Constants.h"
29 #include "llvm/ModuleProvider.h"
3029 #include "llvm/Analysis/Verifier.h"
3130 #include "llvm/Bitcode/ReaderWriter.h"
3231 #include "llvm/ExecutionEngine/GenericValue.h"
2727 #include "llvm/DerivedTypes.h"
2828 #include "llvm/Constants.h"
2929 #include "llvm/Instructions.h"
30 #include "llvm/ModuleProvider.h"
3130 #include "llvm/Analysis/Verifier.h"
3231 #include "llvm/ExecutionEngine/JIT.h"
3332 #include "llvm/ExecutionEngine/Interpreter.h"
3838 #include "llvm/Constants.h"
3939 #include "llvm/DerivedTypes.h"
4040 #include "llvm/Instructions.h"
41 #include "llvm/ModuleProvider.h"
4241 #include "llvm/ExecutionEngine/JIT.h"
4342 #include "llvm/ExecutionEngine/Interpreter.h"
4443 #include "llvm/ExecutionEngine/GenericValue.h"
33 #include "llvm/ExecutionEngine/JIT.h"
44 #include "llvm/LLVMContext.h"
55 #include "llvm/Module.h"
6 #include "llvm/ModuleProvider.h"
76 #include "llvm/PassManager.h"
87 #include "llvm/Analysis/Verifier.h"
98 #include "llvm/Target/TargetData.h"
572571 // Make the module, which holds all the code.
573572 TheModule = new Module("my cool jit", Context);
574573
575 ExistingModuleProvider *OurModuleProvider =
576 new ExistingModuleProvider(TheModule);
577
578 // Create the JIT. This takes ownership of the module and module provider.
579 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
580
581 FunctionPassManager OurFPM(OurModuleProvider);
574 // Create the JIT. This takes ownership of the module.
575 TheExecutionEngine = EngineBuilder(TheModule).create();
576
577 FunctionPassManager OurFPM(TheModule);
582578
583579 // Set up the optimizer pipeline. Start with registering info about how the
584580 // target lays out data structures.
33 #include "llvm/ExecutionEngine/JIT.h"
44 #include "llvm/LLVMContext.h"
55 #include "llvm/Module.h"
6 #include "llvm/ModuleProvider.h"
76 #include "llvm/PassManager.h"
87 #include "llvm/Analysis/Verifier.h"
98 #include "llvm/Target/TargetData.h"
817816 // Make the module, which holds all the code.
818817 TheModule = new Module("my cool jit", Context);
819818
820 ExistingModuleProvider *OurModuleProvider =
821 new ExistingModuleProvider(TheModule);
822
823 // Create the JIT. This takes ownership of the module and module provider.
824 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
825
826 FunctionPassManager OurFPM(OurModuleProvider);
819 // Create the JIT. This takes ownership of the module.
820 TheExecutionEngine = EngineBuilder(TheModule).create();
821
822 FunctionPassManager OurFPM(TheModule);
827823
828824 // Set up the optimizer pipeline. Start with registering info about how the
829825 // target lays out data structures.
33 #include "llvm/ExecutionEngine/JIT.h"
44 #include "llvm/LLVMContext.h"
55 #include "llvm/Module.h"
6 #include "llvm/ModuleProvider.h"
76 #include "llvm/PassManager.h"
87 #include "llvm/Analysis/Verifier.h"
98 #include "llvm/Target/TargetData.h"
935934 // Make the module, which holds all the code.
936935 TheModule = new Module("my cool jit", Context);
937936
938 ExistingModuleProvider *OurModuleProvider =
939 new ExistingModuleProvider(TheModule);
940
941 // Create the JIT. This takes ownership of the module and module provider.
942 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
943
944 FunctionPassManager OurFPM(OurModuleProvider);
937 // Create the JIT. This takes ownership of the module.
938 TheExecutionEngine = EngineBuilder(TheModule).create();
939
940 FunctionPassManager OurFPM(TheModule);
945941
946942 // Set up the optimizer pipeline. Start with registering info about how the
947943 // target lays out data structures.
33 #include "llvm/ExecutionEngine/JIT.h"
44 #include "llvm/LLVMContext.h"
55 #include "llvm/Module.h"
6 #include "llvm/ModuleProvider.h"
76 #include "llvm/PassManager.h"
87 #include "llvm/Analysis/Verifier.h"
98 #include "llvm/Target/TargetData.h"
10991098 // Make the module, which holds all the code.
11001099 TheModule = new Module("my cool jit", Context);
11011100
1102 ExistingModuleProvider *OurModuleProvider =
1103 new ExistingModuleProvider(TheModule);
1104
1105 // Create the JIT. This takes ownership of the module and module provider.
1106 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
1107
1108 FunctionPassManager OurFPM(OurModuleProvider);
1101 // Create the JIT. This takes ownership of the module.
1102 TheExecutionEngine = EngineBuilder(TheModule).create();
1103
1104 FunctionPassManager OurFPM(TheModule);
11091105
11101106 // Set up the optimizer pipeline. Start with registering info about how the
11111107 // target lays out data structures.
2222 #include "llvm/Constants.h"
2323 #include "llvm/DerivedTypes.h"
2424 #include "llvm/Instructions.h"
25 #include "llvm/ModuleProvider.h"
2625 #include "llvm/ExecutionEngine/JIT.h"
2726 #include "llvm/ExecutionEngine/Interpreter.h"
2827 #include "llvm/ExecutionEngine/GenericValue.h"
2626 class MemoryBuffer;
2727
2828 // Forward declare classes
29 class ModuleProvider; // From VMCore
3029 class Module; // From VMCore
3130 class Archive; // Declared below
3231 class ArchiveMemberHeader; // Internal implementation class
373372 /// returns the associated module that defines that symbol. This method can
374373 /// be called as many times as necessary. This is handy for linking the
375374 /// archive into another module based on unresolved symbols. Note that the
376 /// ModuleProvider returned by this accessor should not be deleted by the
377 /// caller. It is managed internally by the Archive class. It is possible
378 /// that multiple calls to this accessor will return the same ModuleProvider
379 /// instance because the associated module defines multiple symbols.
380 /// @returns The ModuleProvider* found or null if the archive does not
381 /// contain a module that defines the \p symbol.
375 /// Module returned by this accessor should not be deleted by the caller. It
376 /// is managed internally by the Archive class. It is possible that multiple
377 /// calls to this accessor will return the same Module instance because the
378 /// associated module defines multiple symbols.
379 /// @returns The Module* found or null if the archive does not contain a
380 /// module that defines the \p symbol.
382381 /// @brief Look up a module by symbol name.
383 ModuleProvider* findModuleDefiningSymbol(
382 Module* findModuleDefiningSymbol(
384383 const std::string& symbol, ///< Symbol to be sought
385384 std::string* ErrMessage ///< Error message storage, if non-zero
386385 );
396395 /// @brief Look up multiple symbols in the archive.
397396 bool findModulesDefiningSymbols(
398397 std::set& symbols, ///< Symbols to be sought
399 std::setProvider*>& modules, ///< The modules matching \p symbols
398 std::set*>& modules, ///< The modules matching \p symbols
400399 std::string* ErrMessage ///< Error msg storage, if non-zero
401400 );
402401
512511
513512 /// This type is used to keep track of bitcode modules loaded from the
514513 /// symbol table. It maps the file offset to a pair that consists of the
515 /// associated ArchiveMember and the ModuleProvider.
514 /// associated ArchiveMember and the Module.
516515 /// @brief Module mapping type
517 typedef std::mapProvider*,ArchiveMember*> >
516 typedef std::map*,ArchiveMember*> >
518517 ModuleMap;
519518
520519
1717
1818 namespace llvm {
1919 class Module;
20 class ModuleProvider;
2120 class MemoryBuffer;
2221 class ModulePass;
2322 class BitstreamWriter;
2423 class LLVMContext;
2524 class raw_ostream;
2625
27 /// getBitcodeModuleProvider - Read the header of the specified bitcode buffer
26 /// getLazyBitcodeModule - Read the header of the specified bitcode buffer
2827 /// and prepare for lazy deserialization of function bodies. If successful,
2928 /// this takes ownership of 'buffer' and returns a non-null pointer. On
3029 /// error, this returns null, *does not* take ownership of Buffer, and fills
3130 /// in *ErrMsg with an error description if ErrMsg is non-null.
32 ModuleProvider *getBitcodeModuleProvider(MemoryBuffer *Buffer,
33 LLVMContext& Context,
34 std::string *ErrMsg = 0);
31 Module *getLazyBitcodeModule(MemoryBuffer *Buffer,
32 LLVMContext& Context,
33 std::string *ErrMsg = 0);
3534
3635 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3736 /// If an error occurs, this returns null and fills in *ErrMsg if it is
3535 class JITMemoryManager;
3636 class MachineCodeInfo;
3737 class Module;
38 class ModuleProvider;
3938 class MutexGuard;
4039 class TargetData;
4140 class Type;
9493 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
9594
9695 protected:
97 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We
98 /// use a smallvector to optimize for the case where there is only one module.
99 SmallVector Modules;
96 /// Modules - This is a list of Modules that we are JIT'ing from. We use a
97 /// smallvector to optimize for the case where there is only one module.
98 SmallVector Modules;
10099
101100 void setTargetData(const TargetData *td) {
102101 TD = td;
108107 // To avoid having libexecutionengine depend on the JIT and interpreter
109108 // libraries, the JIT and Interpreter set these functions to ctor pointers
110109 // at startup time if they are linked in.
111 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP,
110 static ExecutionEngine *(*JITCtor)(Module *M,
112111 std::string *ErrorStr,
113112 JITMemoryManager *JMM,
114113 CodeGenOpt::Level OptLevel,
115114 bool GVsWithCode,
116115 CodeModel::Model CMM);
117 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP,
116 static ExecutionEngine *(*InterpCtor)(Module *M,
118117 std::string *ErrorStr);
119118
120119 /// LazyFunctionCreator - If an unknown function is needed, this function
140139
141140 /// create - This is the factory method for creating an execution engine which
142141 /// is appropriate for the current machine. This takes ownership of the
143 /// module provider.
144 static ExecutionEngine *create(ModuleProvider *MP,
142 /// module.
143 static ExecutionEngine *create(Module *M,
145144 bool ForceInterpreter = false,
146145 std::string *ErrorStr = 0,
147146 CodeGenOpt::Level OptLevel =
164163
165164 /// createJIT - This is the factory method for creating a JIT for the current
166165 /// machine, it does not fall back to the interpreter. This takes ownership
167 /// of the ModuleProvider and JITMemoryManager if successful.
166 /// of the Module and JITMemoryManager if successful.
168167 ///
169168 /// Clients should make sure to initialize targets prior to calling this
170169 /// function.
171 static ExecutionEngine *createJIT(ModuleProvider *MP,
170 static ExecutionEngine *createJIT(Module *M,
172171 std::string *ErrorStr = 0,
173172 JITMemoryManager *JMM = 0,
174173 CodeGenOpt::Level OptLevel =
177176 CodeModel::Model CMM =
178177 CodeModel::Default);
179178
180 /// addModuleProvider - Add a ModuleProvider to the list of modules that we
181 /// can JIT from. Note that this takes ownership of the ModuleProvider: when
182 /// the ExecutionEngine is destroyed, it destroys the MP as well.
183 virtual void addModuleProvider(ModuleProvider *P) {
184 Modules.push_back(P);
179 /// addModule - Add a Module to the list of modules that we can JIT from.
180 /// Note that this takes ownership of the Module: when the ExecutionEngine is
181 /// destroyed, it destroys the Module as well.
182 virtual void addModule(Module *M) {
183 Modules.push_back(M);
185184 }
186185
187186 //===----------------------------------------------------------------------===//
189188 const TargetData *getTargetData() const { return TD; }
190189
191190
192 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
193 /// Relases the Module from the ModuleProvider, materializing it in the
194 /// process, and returns the materialized Module.
195 virtual Module* removeModuleProvider(ModuleProvider *P,
196 std::string *ErrInfo = 0);
197
198 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
199 /// and deletes the ModuleProvider and owned Module. Avoids materializing
200 /// the underlying module.
201 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
191 /// removeModule - Remove a Module from the list of modules. Returns true if
192 /// M is found.
193 virtual bool removeModule(Module *M);
202194
203195 /// FindFunctionNamed - Search all of the active modules to find the one that
204196 /// defines FnName. This is very slow operation and shouldn't be used for
392384 }
393385
394386 protected:
395 explicit ExecutionEngine(ModuleProvider *P);
387 explicit ExecutionEngine(Module *M);
396388
397389 void emitGlobals();
398390
421413 class EngineBuilder {
422414
423415 private:
424 ModuleProvider *MP;
416 Module *M;
425417 EngineKind::Kind WhichEngine;
426418 std::string *ErrorStr;
427419 CodeGenOpt::Level OptLevel;
442434
443435 public:
444436 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
445 /// is successful, the created engine takes ownership of the module
446 /// provider.
447 EngineBuilder(ModuleProvider *mp) : MP(mp) {
437 /// is successful, the created engine takes ownership of the module.
438 EngineBuilder(Module *m) : M(m) {
448439 InitEngine();
449440 }
450
451 /// EngineBuilder - Overloaded constructor that automatically creates an
452 /// ExistingModuleProvider for an existing module.
453 EngineBuilder(Module *m);
454441
455442 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
456443 /// or whichever engine works. This option defaults to EngineKind::Either.
0 //===-- llvm/GVMaterializer.h - Interface for GV materializers --*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides an abstract interface for loading a module from some
10 // place. This interface allows incremental or random access loading of
11 // functions from the file. This is useful for applications like JIT compilers
12 // or interprocedural optimizers that do not need the entire program in memory
13 // at the same time.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef GVMATERIALIZER_H
18 #define GVMATERIALIZER_H
19
20 #include
21
22 namespace llvm {
23
24 class Function;
25 class GlobalValue;
26 class Module;
27
28 class GVMaterializer {
29 protected:
30 GVMaterializer() {}
31
32 public:
33 virtual ~GVMaterializer();
34
35 /// isMaterializable - True if GV can be materialized from whatever backing
36 /// store this GVMaterializer uses and has not been materialized yet.
37 virtual bool isMaterializable(const GlobalValue *GV) const = 0;
38
39 /// isDematerializable - True if GV has been materialized and can be
40 /// dematerialized back to whatever backing store this GVMaterializer uses.
41 virtual bool isDematerializable(const GlobalValue *GV) const = 0;
42
43 /// Materialize - make sure the given GlobalValue is fully read. If the
44 /// module is corrupt, this returns true and fills in the optional string with
45 /// information about the problem. If successful, this returns false.
46 ///
47 virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0) = 0;
48
49 /// Dematerialize - If the given GlobalValue is read in, and if the
50 /// GVMaterializer supports it, release the memory for the GV, and set it up
51 /// to be materialized lazily. If the Materializer doesn't support this
52 /// capability, this method is a noop.
53 ///
54 virtual void Dematerialize(GlobalValue *) {}
55
56 /// MaterializeModule - make sure the entire Module has been completely read.
57 /// On error, this returns true and fills in the optional string with
58 /// information about the problem. If successful, this returns false.
59 ///
60 virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0) = 0;
61 };
62
63 } // End llvm namespace
64
65 #endif
4242 DLLImportLinkage, ///< Function to be imported from DLL
4343 DLLExportLinkage, ///< Function to be accessible from DLL.
4444 ExternalWeakLinkage,///< ExternalWeak linkage description.
45 GhostLinkage, ///< Stand-in functions for streaming fns from BC files.
4645 CommonLinkage ///< Tentative definitions.
4746 };
4847
131130 bool hasDLLImportLinkage() const { return Linkage == DLLImportLinkage; }
132131 bool hasDLLExportLinkage() const { return Linkage == DLLExportLinkage; }
133132 bool hasExternalWeakLinkage() const { return Linkage == ExternalWeakLinkage; }
134 bool hasGhostLinkage() const { return Linkage == GhostLinkage; }
135133 bool hasCommonLinkage() const { return Linkage == CommonLinkage; }
136134
137135 void setLinkage(LinkageTypes LT) { Linkage = LT; }
163161 /// create a GlobalValue) from the GlobalValue Src to this one.
164162 virtual void copyAttributesFrom(const GlobalValue *Src);
165163
166 /// hasNotBeenReadFromBitcode - If a module provider is being used to lazily
167 /// stream in functions from disk, this method can be used to check to see if
168 /// the function has been read in yet or not. Unless you are working on the
169 /// JIT or something else that streams stuff in lazily, you don't need to
170 /// worry about this.
171 bool hasNotBeenReadFromBitcode() const { return Linkage == GhostLinkage; }
164 /// @name Materialization
165 /// Materialization is used to construct functions only as they're needed. This
166 /// is useful to reduce memory usage in LLVM or parsing work done by the
167 /// BitcodeReader to load the Module.
168 /// @{
169
170 /// isMaterializable - If this function's Module is being lazily streamed in
171 /// functions from disk or some other source, this method can be used to check
172 /// to see if the function has been read in yet or not.
173 bool isMaterializable() const;
174
175 /// isDematerializable - Returns true if this function was loaded from a
176 /// GVMaterializer that's still attached to its Module and that knows how to
177 /// dematerialize the function.
178 bool isDematerializable() const;
179
180 /// Materialize - make sure this GlobalValue is fully read. If the module is
181 /// corrupt, this returns true and fills in the optional string with
182 /// information about the problem. If successful, this returns false.
183 bool Materialize(std::string *ErrInfo = 0);
184
185 /// Dematerialize - If this GlobalValue is read in, and if the GVMaterializer
186 /// supports it, release the memory for the function, and set it up to be
187 /// materialized lazily. If !isDematerializable(), this method is a noop.
188 void Dematerialize();
189
190 /// @}
172191
173192 /// Override from Constant class. No GlobalValue's are null values so this
174193 /// always returns false.
1818 #include "llvm/GlobalVariable.h"
1919 #include "llvm/GlobalAlias.h"
2020 #include "llvm/Metadata.h"
21 #include "llvm/ADT/OwningPtr.h"
2122 #include "llvm/System/DataTypes.h"
2223 #include
2324
2425 namespace llvm {
2526
2627 class FunctionType;
28 class GVMaterializer;
2729 class LLVMContext;
2830 class MDSymbolTable;
2931
144146 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
145147 ValueSymbolTable *ValSymTab; ///< Symbol table for values
146148 TypeSymbolTable *TypeSymTab; ///< Symbol table for types
149 OwningPtr Materializer; ///< Used to materialize GlobalValues
147150 std::string ModuleID; ///< Human readable identifier for the module
148151 std::string TargetTriple; ///< Platform target triple Module compiled on
149152 std::string DataLayout; ///< Target data description
344347 /// getTypeByName - Return the type with the specified name in this module, or
345348 /// null if there is none by that name.
346349 const Type *getTypeByName(StringRef Name) const;
350
351 /// @}
352 /// @name Materialization
353 /// @{
354
355 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
356 /// yet have a Materializer. To reset the materializer for a module that
357 /// already has one, call MaterializeAllPermanently first. Destroying this
358 /// module will destroy its materializer without materializing any more
359 /// GlobalValues. Without destroying the Module, there is no way to detach or
360 /// destroy a materializer without materializing all the GVs it controls, to
361 /// avoid leaving orphan unmaterialized GVs.
362 void setMaterializer(GVMaterializer *GVM);
363 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
364 GVMaterializer *getMaterializer() const { return Materializer.get(); }
365
366 /// isMaterializable - True if the definition of GV has yet to be materialized
367 /// from the GVMaterializer.
368 bool isMaterializable(const GlobalValue *GV) const;
369 /// isDematerializable - Returns true if this GV was loaded from this Module's
370 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
371 bool isDematerializable(const GlobalValue *GV) const;
372
373 /// Materialize - Make sure the GlobalValue is fully read. If the module is
374 /// corrupt, this returns true and fills in the optional string with
375 /// information about the problem. If successful, this returns false.
376 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
377 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
378 /// supports it, release the memory for the function, and set it up to be
379 /// materialized lazily. If !isDematerializable(), this method is a noop.
380 void Dematerialize(GlobalValue *GV);
381
382 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
383 /// If the module is corrupt, this returns true and fills in the optional
384 /// string with information about the problem. If successful, this returns
385 /// false.
386 bool MaterializeAll(std::string *ErrInfo = 0);
387
388 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
389 /// fully read and clear the Materializer. If the module is corrupt, this
390 /// returns true, fills in the optional string with information about the
391 /// problem, and DOES NOT clear the old Materializer. If successful, this
392 /// returns false.
393 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
347394
348395 /// @}
349396 /// @name Direct access to the globals list, functions list, and symbol table
+0
-88
include/llvm/ModuleProvider.h less more
None //===-- llvm/ModuleProvider.h - Interface for module providers --*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides an abstract interface for loading a module from some
10 // place. This interface allows incremental or random access loading of
11 // functions from the file. This is useful for applications like JIT compilers
12 // or interprocedural optimizers that do not need the entire program in memory
13 // at the same time.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef MODULEPROVIDER_H
18 #define MODULEPROVIDER_H
19
20 #include
21
22 namespace llvm {
23
24 class Function;
25 class Module;
26
27 class ModuleProvider {
28 protected:
29 Module *TheModule;
30 ModuleProvider();
31
32 public:
33 virtual ~ModuleProvider();
34
35 /// getModule - returns the module this provider is encapsulating.
36 ///
37 Module* getModule() { return TheModule; }
38
39 /// materializeFunction - make sure the given function is fully read. If the
40 /// module is corrupt, this returns true and fills in the optional string
41 /// with information about the problem. If successful, this returns false.
42 ///
43 virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0) = 0;
44
45 /// dematerializeFunction - If the given function is read in, and if the
46 /// module provider supports it, release the memory for the function, and set
47 /// it up to be materialized lazily. If the provider doesn't support this
48 /// capability, this method is a noop.
49 ///
50 virtual void dematerializeFunction(Function *) {}
51
52 /// materializeModule - make sure the entire Module has been completely read.
53 /// On error, return null and fill in the error string if specified.
54 ///
55 virtual Module* materializeModule(std::string *ErrInfo = 0) = 0;
56
57 /// releaseModule - no longer delete the Module* when provider is destroyed.
58 /// On error, return null and fill in the error string if specified.
59 ///
60 virtual Module* releaseModule(std::string *ErrInfo = 0) {
61 // Since we're losing control of this Module, we must hand it back complete
62 if (!materializeModule(ErrInfo))
63 return 0;
64 Module *tempM = TheModule;
65 TheModule = 0;
66 return tempM;
67 }
68 };
69
70
71 /// ExistingModuleProvider - Allow conversion from a fully materialized Module
72 /// into a ModuleProvider, allowing code that expects a ModuleProvider to work
73 /// if we just have a Module. Note that the ModuleProvider takes ownership of
74 /// the Module specified.
75 struct ExistingModuleProvider : public ModuleProvider {
76 explicit ExistingModuleProvider(Module *M) {
77 TheModule = M;
78 }
79 bool materializeFunction(Function *, std::string * = 0) {
80 return false;
81 }
82 Module* materializeModule(std::string * = 0) { return TheModule; }
83 };
84
85 } // End llvm namespace
86
87 #endif
2323 class Pass;
2424 class ModulePass;
2525 class Module;
26 class ModuleProvider;
2726
2827 class PassManagerImpl;
2928 class FunctionPassManagerImpl;
7069 class FunctionPassManager : public PassManagerBase {
7170 public:
7271 /// FunctionPassManager ctor - This initializes the pass manager. It needs,
73 /// but does not take ownership of, the specified module provider.
74 explicit FunctionPassManager(ModuleProvider *P);
72 /// but does not take ownership of, the specified Module.
73 explicit FunctionPassManager(Module *M);
7574 ~FunctionPassManager();
7675
7776 /// add - Add a pass to the queue of passes to run. This passes
9594 ///
9695 bool doFinalization();
9796
98 /// getModuleProvider - Return the module provider that this passmanager is
99 /// currently using. This is the module provider that it uses when a function
100 /// is optimized that is non-resident in the module.
101 ModuleProvider *getModuleProvider() const { return MP; }
102 void setModuleProvider(ModuleProvider *NewMP) { MP = NewMP; }
103
10497 private:
10598 FunctionPassManagerImpl *FPM;
106 ModuleProvider *MP;
99 Module *M;
107100 };
108101
109102 } // End llvm namespace
2222 #include "llvm/Bitcode/ReaderWriter.h"
2323 #include "llvm/Support/MemoryBuffer.h"
2424 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/ModuleProvider.h"
2625
2726 namespace llvm {
2827
29 /// If the given MemoryBuffer holds a bitcode image, return a ModuleProvider
30 /// for it which does lazy deserialization of function bodies. Otherwise,
31 /// attempt to parse it as LLVM Assembly and return a fully populated
32 /// ModuleProvider. This function *always* takes ownership of the given
33 /// MemoryBuffer.
34 inline ModuleProvider *getIRModuleProvider(MemoryBuffer *Buffer,
35 SMDiagnostic &Err,
36 LLVMContext &Context) {
28 /// If the given MemoryBuffer holds a bitcode image, return a Module for it
29 /// which does lazy deserialization of function bodies. Otherwise, attempt to
30 /// parse it as LLVM Assembly and return a fully populated Module. This
31 /// function *always* takes ownership of the given MemoryBuffer.
32 inline Module *getIRModule(MemoryBuffer *Buffer,
33 SMDiagnostic &Err,
34 LLVMContext &Context) {
3735 if (isBitcode((const unsigned char *)Buffer->getBufferStart(),
3836 (const unsigned char *)Buffer->getBufferEnd())) {
3937 std::string ErrMsg;
40 ModuleProvider *MP = getBitcodeModuleProvider(Buffer, Context, &ErrMsg);
41 if (MP == 0) {
38 Module *M = getLazyBitcodeModule(Buffer, Context, &ErrMsg);
39 if (M == 0) {
4240 Err = SMDiagnostic(Buffer->getBufferIdentifier(), -1, -1, ErrMsg, "");
4341 // ParseBitcodeFile does not take ownership of the Buffer in the
4442 // case of an error.
4543 delete Buffer;
4644 }
47 return MP;
45 return M;
4846 }
4947
50 Module *M = ParseAssembly(Buffer, 0, Err, Context);
51 if (M == 0)
52 return 0;
53 return new ExistingModuleProvider(M);
48 return ParseAssembly(Buffer, 0, Err, Context);
5449 }
5550
56 /// If the given file holds a bitcode image, return a ModuleProvider
51 /// If the given file holds a bitcode image, return a Module
5752 /// for it which does lazy deserialization of function bodies. Otherwise,
5853 /// attempt to parse it as LLVM Assembly and return a fully populated
59 /// ModuleProvider.
60 inline ModuleProvider *getIRFileModuleProvider(const std::string &Filename,
61 SMDiagnostic &Err,
62 LLVMContext &Context) {
54 /// Module.
55 inline Module *getIRFileModule(const std::string &Filename,
56 SMDiagnostic &Err,
57 LLVMContext &Context) {
6358 std::string ErrMsg;
6459 MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), &ErrMsg);
6560 if (F == 0) {
6863 return 0;
6964 }
7065
71 return getIRModuleProvider(F, Err, Context);
66 return getIRModule(F, Err, Context);
7267 }
7368
7469 /// If the given MemoryBuffer holds a bitcode image, return a Module
7777 typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;
7878 typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;
7979
80 /* Used to provide a module to JIT or interpreter.
81 * See the llvm::ModuleProvider class.
80 /* Interface used to provide a module to JIT or interpreter. This is now just a
81 * synonym for llvm::Module, but we have to keep using the different type to
82 * keep binary compatibility.
8283 */
8384 typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef;
8485
209210 LLVMDLLImportLinkage, /**< Function to be imported from DLL */
210211 LLVMDLLExportLinkage, /**< Function to be accessible from DLL */
211212 LLVMExternalWeakLinkage,/**< ExternalWeak linkage description */
212 LLVMGhostLinkage, /**< Stand-in functions for streaming fns from
213 bitcode */
213 LLVMGhostLinkage, /**< Obsolete */
214214 LLVMCommonLinkage, /**< Tentative definitions */
215215 LLVMLinkerPrivateLinkage /**< Like Private, but linker removes. */
216216 } LLVMLinkage;
913913
914914 /*===-- Module providers --------------------------------------------------===*/
915915
916 /* Encapsulates the module M in a module provider, taking ownership of the
917 * module.
918 * See the constructor llvm::ExistingModuleProvider::ExistingModuleProvider.
916 /* Changes the type of M so it can be passed to FunctionPassManagers and the
917 * JIT. They take ModuleProviders for historical reasons.
919918 */
920919 LLVMModuleProviderRef
921920 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M);
922921
923 /* Destroys the module provider MP as well as the contained module.
924 * See the destructor llvm::ModuleProvider::~ModuleProvider.
925 */
926 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP);
922 /* Destroys the module M.
923 */
924 void LLVMDisposeModuleProvider(LLVMModuleProviderRef M);
927925
928926
929927 /*===-- Memory buffers ----------------------------------------------------===*/
980978 }
981979
982980 namespace llvm {
983 class ModuleProvider;
984981 class MemoryBuffer;
985982 class PassManagerBase;
986983
10171014 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef )
10181015 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef )
10191016 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(PATypeHolder, LLVMTypeHandleRef )
1020 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ModuleProvider, LLVMModuleProviderRef)
10211017 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer, LLVMMemoryBufferRef )
10221018 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef )
10231019 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Use, LLVMUseIteratorRef )
10241020 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBase, LLVMPassManagerRef )
1021 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
1022 * Module.
1023 */
1024 inline Module *unwrap(LLVMModuleProviderRef MP) {
1025 return reinterpret_cast(MP);
1026 }
10251027
10261028 #undef DEFINE_STDCXX_CONVERSION_FUNCTIONS
10271029 #undef DEFINE_ISA_CONVERSION_FUNCTIONS
1313
1414 #include "ArchiveInternals.h"
1515 #include "llvm/Bitcode/ReaderWriter.h"
16 #include "llvm/ModuleProvider.h"
1716 #include "llvm/Module.h"
1817 #include "llvm/Support/MemoryBuffer.h"
1918 #include "llvm/System/Process.h"
172171 foreignST = 0;
173172 }
174173
175 // Delete any ModuleProviders and ArchiveMember's we've allocated as a result
176 // of symbol table searches.
174 // Delete any Modules and ArchiveMember's we've allocated as a result of
175 // symbol table searches.
177176 for (ModuleMap::iterator I=modules.begin(), E=modules.end(); I != E; ++I ) {
178177 delete I->second.first;
179178 delete I->second.second;
220219 return true;
221220 }
222221
223 ModuleProvider *MP = getBitcodeModuleProvider(Buffer.get(), Context, ErrMsg);
224 if (!MP)
225 return true;
226
227 // Get the module from the provider
228 Module* M = MP->materializeModule();
229 if (M == 0) {
230 delete MP;
231 return true;
232 }
222 Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg);
223 if (!M)
224 return true;
233225
234226 // Get the symbols
235227 getSymbols(M, symbols);
236228
237229 // Done with the module.
238 delete MP;
230 delete M;
239231 return true;
240232 }
241233
242 ModuleProvider*
234 Module*
243235 llvm::GetBitcodeSymbols(const unsigned char *BufPtr, unsigned Length,
244236 const std::string& ModuleID,
245237 LLVMContext& Context,
246238 std::vector& symbols,
247239 std::string* ErrMsg) {
248 // Get the module provider
249 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(Length, ModuleID.c_str());
240 // Get the module.
241 std::auto_ptr Buffer(
242 MemoryBuffer::getNewMemBuffer(Length, ModuleID.c_str()));
250243 memcpy((char*)Buffer->getBufferStart(), BufPtr, Length);
251244
252 ModuleProvider *MP = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
253 if (!MP)
245 Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg);
246 if (!M)
254247 return 0;
255
256 // Get the module from the provider
257 Module* M = MP->materializeModule();
258 if (M == 0) {
259 delete MP;
260 return 0;
261 }
262248
263249 // Get the symbols
264250 getSymbols(M, symbols);
265251
266 // Done with the module. Note that ModuleProvider will delete the
267 // Module when it is deleted. Also note that its the caller's responsibility
268 // to delete the ModuleProvider.
269 return MP;
270 }
252 // Done with the module. Note that it's the caller's responsibility to delete
253 // the Module.
254 return M;
255 }
7676 std::vector& symbols,
7777 std::string* ErrMsg);
7878
79 ModuleProvider* GetBitcodeSymbols(const unsigned char*Buffer,unsigned Length,
80 const std::string& ModuleID,
81 LLVMContext& Context,
82 std::vector& symbols,
83 std::string* ErrMsg);
79 Module* GetBitcodeSymbols(const unsigned char*Buffer,unsigned Length,
80 const std::string& ModuleID,
81 LLVMContext& Context,
82 std::vector& symbols,
83 std::string* ErrMsg);
8484 }
8585
8686 #endif
451451 return result.release();
452452 }
453453
454 // Look up one symbol in the symbol table and return a ModuleProvider for the
455 // module that defines that symbol.
456 ModuleProvider*
454 // Look up one symbol in the symbol table and return the module that defines
455 // that symbol.
456 Module*
457457 Archive::findModuleDefiningSymbol(const std::string& symbol,
458458 std::string* ErrMsg) {
459459 SymTabType::iterator SI = symTab.find(symbol);
482482 if (!mbr)
483483 return 0;
484484
485 // Now, load the bitcode module to get the ModuleProvider
485 // Now, load the bitcode module to get the Module.
486486 std::string FullMemberName = archPath.str() + "(" +
487487 mbr->getPath().str() + ")";
488488 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
489489 FullMemberName.c_str());
490490 memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
491491
492 ModuleProvider *mp = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
493 if (!mp)
494 return 0;
495
496 modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
497
498 return mp;
492 Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
493 if (!m)
494 return 0;
495
496 modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
497
498 return m;
499499 }
500500
501501 // Look up multiple symbols in the symbol table and return a set of
502 // ModuleProviders that define those symbols.
502 // Modules that define those symbols.
503503 bool
504504 Archive::findModulesDefiningSymbols(std::set& symbols,
505 std::setProvider*>& result,
505 std::set*>& result,
506506 std::string* error) {
507507 if (!mapfile || !base) {
508508 if (error)
535535 std::vector symbols;
536536 std::string FullMemberName = archPath.str() + "(" +
537537 mbr->getPath().str() + ")";
538 ModuleProvider* MP =
538 Module* M =
539539 GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(),
540540 FullMemberName, Context, symbols, error);
541541
542 if (MP) {
542 if (M) {
543543 // Insert the module's symbols into the symbol table
544544 for (std::vector::iterator I = symbols.begin(),
545545 E=symbols.end(); I != E; ++I ) {
546546 symTab.insert(std::make_pair(*I, offset));
547547 }
548 // Insert the ModuleProvider and the ArchiveMember into the table of
548 // Insert the Module and the ArchiveMember into the table of
549549 // modules.
550 modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
550 modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
551551 } else {
552552 if (error)
553553 *error = "Can't parse bitcode member: " +
570570 for (std::set::iterator I=symbols.begin(),
571571 E=symbols.end(); I != E;) {
572572 // See if this symbol exists
573 ModuleProvider* mp = findModuleDefiningSymbol(*I,error);
574 if (mp) {
575 // The symbol exists, insert the ModuleProvider into our result,
576 // duplicates wil be ignored
577 result.insert(mp);
573 Module* m = findModuleDefiningSymbol(*I,error);
574 if (m) {
575 // The symbol exists, insert the Module into our result, duplicates will
576 // be ignored.
577 result.insert(m);
578578
579579 // Remove the symbol now that its been resolved, being careful to
580580 // post-increment the iterator.
1111 //===----------------------------------------------------------------------===//
1212
1313 #include "ArchiveInternals.h"
14 #include "llvm/Module.h"
15 #include "llvm/ADT/OwningPtr.h"
1416 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/ADT/OwningPtr.h"
1617 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/System/Process.h"
1719 #include "llvm/System/Signals.h"
18 #include "llvm/System/Process.h"
19 #include "llvm/ModuleProvider.h"
2020 #include
2121 #include
2222 #include
224224 std::vector symbols;
225225 std::string FullMemberName = archPath.str() + "(" + member.getPath().str()
226226 + ")";
227 ModuleProvider* MP =
227 Module* M =
228228 GetBitcodeSymbols((const unsigned char*)data,fSize,
229229 FullMemberName, Context, symbols, ErrMsg);
230230
231231 // If the bitcode parsed successfully
232 if ( MP ) {
232 if ( M ) {
233233 for (std::vector::iterator SI = symbols.begin(),
234234 SE = symbols.end(); SI != SE; ++SI) {
235235
243243 }
244244 }
245245 // We don't need this module any more.
246 delete MP;
246 delete M;
247247 } else {
248248 delete mFile;
249249 if (ErrMsg)
25652565 return Error(LinkageLoc, "invalid linkage for function declaration");
25662566 break;
25672567 case GlobalValue::AppendingLinkage:
2568 case GlobalValue::GhostLinkage:
25692568 case GlobalValue::CommonLinkage:
25702569 return Error(LinkageLoc, "invalid function linkage type");
25712570 }
5858 char **OutMessage) {
5959 std::string Message;
6060
61 *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), getGlobalContext(),
62 &Message));
61 *OutMP = reinterpret_cast(
62 getLazyBitcodeModule(unwrap(MemBuf), getGlobalContext(), &Message));
6363
6464 if (!*OutMP) {
6565 if (OutMessage)
7676 char **OutMessage) {
7777 std::string Message;
7878
79 *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), *unwrap(ContextRef),
80 &Message));
79 *OutMP = reinterpret_cast(
80 getLazyBitcodeModule(unwrap(MemBuf), *unwrap(ContextRef), &Message));
8181 if (!*OutMP) {
8282 if (OutMessage)
8383 *OutMessage = strdup(Message.c_str());
2727 using namespace llvm;
2828
2929 void BitcodeReader::FreeState() {
30 delete Buffer;
30 if (BufferOwned)
31 delete Buffer;
3132 Buffer = 0;
3233 std::vector().swap(TypeList);
3334 ValueList.clear();
12401241
12411242 // Save the current stream state.
12421243 uint64_t CurBit = Stream.GetCurrentBitNo();
1243 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1244
1245 // Set the functions linkage to GhostLinkage so we know it is lazily
1246 // deserialized.
1247 Fn->setLinkage(GlobalValue::GhostLinkage);
1244 DeferredFunctionInfo[Fn] = CurBit;
12481245
12491246 // Skip over the function block for now.
12501247 if (Stream.SkipBlock())
12521249 return false;
12531250 }
12541251
1255 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1256 // Reject multiple MODULE_BLOCK's in a single bitstream.
1257 if (TheModule)
1258 return Error("Multiple MODULE_BLOCKs in same stream");
1259
1252 bool BitcodeReader::ParseModule() {
12601253 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
12611254 return Error("Malformed block record");
1262
1263 // Otherwise, create the module.
1264 TheModule = new Module(ModuleID, Context);
12651255
12661256 SmallVector Record;
12671257 std::vector SectionTable;
15191509 return Error("Premature end of bitstream");
15201510 }
15211511
1522 bool BitcodeReader::ParseBitcode() {
1512 bool BitcodeReader::ParseBitcodeInto(Module *M) {
15231513 TheModule = 0;
15241514
15251515 if (Buffer->getBufferSize() & 3)
15631553 return Error("Malformed BlockInfoBlock");
15641554 break;
15651555 case bitc::MODULE_BLOCK_ID:
1566 if (ParseModule(Buffer->getBufferIdentifier()))
1556 // Reject multiple MODULE_BLOCK's in a single bitstream.
1557 if (TheModule)
1558 return Error("Multiple MODULE_BLOCKs in same stream");
1559 TheModule = M;
1560 if (ParseModule())
15671561 return true;
15681562 break;
15691563 default:
22982292 }
22992293
23002294 //===----------------------------------------------------------------------===//
2301 // ModuleProvider implementation
2295 // GVMaterializer implementation
23022296 //===----------------------------------------------------------------------===//
23032297
23042298
2305 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2306 // If it already is material, ignore the request.
2307 if (!F->hasNotBeenReadFromBitcode()) return false;
2308
2309 DenseMap >::iterator DFII =
2310 DeferredFunctionInfo.find(F);
2299 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2300 if (const Function *F = dyn_cast(GV)) {
2301 return F->isDeclaration() &&
2302 DeferredFunctionInfo.count(const_cast(F));
2303 }
2304 return false;
2305 }
2306
2307 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2308 Function *F = dyn_cast(GV);
2309 // If it's not a function or is already material, ignore the request.
2310 if (!F || !F->isMaterializable()) return false;
2311
2312 DenseMap::iterator DFII = DeferredFunctionInfo.find(F);
23112313 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
23122314
2313 // Move the bit stream to the saved position of the deferred function body and
2314 // restore the real linkage type for the function.
2315 Stream.JumpToBit(DFII->second.first);
2316 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2315 // Move the bit stream to the saved position of the deferred function body.
2316 Stream.JumpToBit(DFII->second);
23172317
23182318 if (ParseFunctionBody(F)) {
23192319 if (ErrInfo) *ErrInfo = ErrorString;
23352335 return false;
23362336 }
23372337
2338 void BitcodeReader::dematerializeFunction(Function *F) {
2339 // If this function isn't materialized, or if it is a proto, this is a noop.
2340 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2338 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2339 const Function *F = dyn_cast(GV);
2340 if (!F || F->isDeclaration())
2341 return false;
2342 return DeferredFunctionInfo.count(const_cast(F));
2343 }
2344
2345 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2346 Function *F = dyn_cast(GV);
2347 // If this function isn't dematerializable, this is a noop.
2348 if (!F || !isDematerializable(F))
23412349 return;
23422350
23432351 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
23442352
23452353 // Just forget the function body, we can remat it later.
23462354 F->deleteBody();
2347 F->setLinkage(GlobalValue::GhostLinkage);
2348 }
2349
2350
2351 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2355 }
2356
2357
2358 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2359 assert(M == TheModule &&
2360 "Can only Materialize the Module this BitcodeReader is attached to.");
23522361 // Iterate over the module, deserializing any functions that are still on
23532362 // disk.
23542363 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
23552364 F != E; ++F)
2356 if (F->hasNotBeenReadFromBitcode() &&
2357 materializeFunction(F, ErrInfo))
2358 return 0;
2365 if (F->isMaterializable() &&
2366 Materialize(F, ErrInfo))
2367 return true;
23592368
23602369 // Upgrade any intrinsic calls that slipped through (should not happen!) and
23612370 // delete the old functions to clean up. We can't do this unless the entire
23792388 // Check debug info intrinsics.
23802389 CheckDebugInfoIntrinsics(TheModule);
23812390
2382 return TheModule;
2383 }
2384
2385
2386 /// This method is provided by the parent ModuleProvde class and overriden
2387 /// here. It simply releases the module from its provided and frees up our
2388 /// state.
2389 /// @brief Release our hold on the generated module
2390 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2391 // Since we're losing control of this Module, we must hand it back complete
2392 Module *M = ModuleProvider::releaseModule(ErrInfo);
2393 FreeState();
2394 return M;
2391 return false;
23952392 }
23962393
23972394
23992396 // External interface
24002397 //===----------------------------------------------------------------------===//
24012398
2402 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2399 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
24032400 ///
2404 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2405 LLVMContext& Context,
2406 std::string *ErrMsg) {
2401 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2402 LLVMContext& Context,
2403 std::string *ErrMsg) {
2404 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
24072405 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2408 if (R->ParseBitcode()) {
2406 M->setMaterializer(R);
2407 if (R->ParseBitcodeInto(M)) {
24092408 if (ErrMsg)
24102409 *ErrMsg = R->getErrorString();
24112410
2412 // Don't let the BitcodeReader dtor delete 'Buffer'.
2413 R->releaseMemoryBuffer();
2414 delete R;
2411 delete M; // Also deletes R.
24152412 return 0;
24162413 }
2417 return R;
2414 // Have the BitcodeReader dtor delete 'Buffer'.
2415 R->setBufferOwned(true);
2416 return M;
24182417 }
24192418
24202419 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
24212420 /// If an error occurs, return null and fill in *ErrMsg if non-null.
24222421 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
24232422 std::string *ErrMsg){
2424 BitcodeReader *R;
2425 R = static_cast(getBitcodeModuleProvider(Buffer, Context,
2426 ErrMsg));
2427 if (!R) return 0;
2428
2429 // Read in the entire module.
2430 Module *M = R->materializeModule(ErrMsg);
2423 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2424 if (!M) return 0;
24312425
24322426 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
24332427 // there was an error.
2434 R->releaseMemoryBuffer();
2435
2436 // If there was no error, tell ModuleProvider not to delete it when its dtor
2437 // is run.
2438 if (M)
2439 M = R->releaseModule(ErrMsg);
2440
2441 delete R;
2428 static_cast(M->getMaterializer())->setBufferOwned(false);
2429
2430 // Read in the entire module, and destroy the BitcodeReader.
2431 if (M->MaterializeAllPermanently(ErrMsg)) {
2432 delete M;
2433 return NULL;
2434 }
24422435 return M;
24432436 }
1313 #ifndef BITCODE_READER_H
1414 #define BITCODE_READER_H
1515
16 #include "llvm/ModuleProvider.h"
16 #include "llvm/GVMaterializer.h"
1717 #include "llvm/Attributes.h"
1818 #include "llvm/Type.h"
1919 #include "llvm/OperandTraits.h"
120120 void AssignValue(Value *V, unsigned Idx);
121121 };
122122
123 class BitcodeReader : public ModuleProvider {
123 class BitcodeReader : public GVMaterializer {
124124 LLVMContext &Context;
125 Module *TheModule;
125126 MemoryBuffer *Buffer;
127 bool BufferOwned;
126128 BitstreamReader StreamFile;
127129 BitstreamCursor Stream;
128130
159161 bool HasReversedFunctionsWithBodies;
160162
161163 /// DeferredFunctionInfo - When function bodies are initially scanned, this
162 /// map contains info about where to find deferred function body (in the
163 /// stream) and what linkage the original function had.
164 DenseMap > DeferredFunctionInfo;
164 /// map contains info about where to find deferred function body in the
165 /// stream.
166 DenseMap DeferredFunctionInfo;
165167
166168 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
167169 /// are resolved lazily when functions are loaded.
170172
171173 public:
172174 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
173 : Context(C), Buffer(buffer), ErrorString(0), ValueList(C), MDValueList(C) {
175 : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
176 ErrorString(0), ValueList(C), MDValueList(C) {
174177 HasReversedFunctionsWithBodies = false;
175178 }
176179 ~BitcodeReader() {
179182
180183 void FreeState();
181184
182 /// releaseMemoryBuffer - This causes the reader to completely forget about
183 /// the memory buffer it contains, which prevents the buffer from being
184 /// destroyed when it is deleted.
185 void releaseMemoryBuffer() {
186 Buffer = 0;
187 }
188
189 virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
190 virtual Module *materializeModule(std::string *ErrInfo = 0);
191 virtual void dematerializeFunction(Function *F);
192 virtual Module *releaseModule(std::string *ErrInfo = 0);
185 /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
186 /// when the reader is destroyed.
187 void setBufferOwned(bool Owned) { BufferOwned = Owned; }
188
189 virtual bool isMaterializable(const GlobalValue *GV) const;
190 virtual bool isDematerializable(const GlobalValue *GV) const;
191 virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
192 virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
193 virtual void Dematerialize(GlobalValue *GV);
193194
194195 bool Error(const char *Str) {
195196 ErrorString = Str;
199200
200201 /// @brief Main interface to parsing a bitcode buffer.
201202 /// @returns true if an error occurred.
202 bool ParseBitcode();
203 bool ParseBitcodeInto(Module *M);
203204 private:
204205 const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
205206 Value *getFnValueByID(unsigned ID, const Type *Ty) {
247248 }
248249
249250
250 bool ParseModule(const std::string &ModuleID);
251 bool ParseModule();
251252 bool ParseAttributeBlock();
252253 bool ParseTypeTable();
253254 bool ParseTypeSymbolTable();
279279 static unsigned getEncodedLinkage(const GlobalValue *GV) {
280280 switch (GV->getLinkage()) {
281281 default: llvm_unreachable("Invalid linkage!");
282 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
283282 case GlobalValue::ExternalLinkage: return 0;
284283 case GlobalValue::WeakAnyLinkage: return 1;
285284 case GlobalValue::AppendingLinkage: return 2;
1717 #include "llvm/Constants.h"
1818 #include "llvm/DerivedTypes.h"
1919 #include "llvm/Module.h"
20 #include "llvm/ModuleProvider.h"
2120 #include "llvm/ExecutionEngine/GenericValue.h"
2221 #include "llvm/ADT/Statistic.h"
2322 #include "llvm/Support/Debug.h"
3534 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
3635 STATISTIC(NumGlobals , "Number of global vars initialized");
3736
38 ExecutionEngine *(*ExecutionEngine::JITCtor)(ModuleProvider *MP,
37 ExecutionEngine *(*ExecutionEngine::JITCtor)(Module *M,
3938 std::string *ErrorStr,
4039 JITMemoryManager *JMM,
4140 CodeGenOpt::Level OptLevel,
4241 bool GVsWithCode,
4342 CodeModel::Model CMM) = 0;
44 ExecutionEngine *(*ExecutionEngine::InterpCtor)(ModuleProvider *MP,
43 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
4544 std::string *ErrorStr) = 0;
4645 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
4746
4847
49 ExecutionEngine::ExecutionEngine(ModuleProvider *P)
48 ExecutionEngine::ExecutionEngine(Module *M)
5049 : EEState(*this),
5150 LazyFunctionCreator(0) {
5251 CompilingLazily = false;
5352 GVCompilationDisabled = false;
5453 SymbolSearchingDisabled = false;
55 Modules.push_back(P);
56 assert(P && "ModuleProvider is null?");
54 Modules.push_back(M);
55 assert(M && "Module is null?");
5756 }
5857
5958 ExecutionEngine::~ExecutionEngine() {
6867 return new char[GVSize];
6968 }
7069
71 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
72 /// Relases the Module from the ModuleProvider, materializing it in the
73 /// process, and returns the materialized Module.
74 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
75 std::string *ErrInfo) {
76 for(SmallVector::iterator I = Modules.begin(),
70 /// removeModule - Remove a Module from the list of modules.
71 bool ExecutionEngine::removeModule(Module *M) {
72 for(SmallVector::iterator I = Modules.begin(),
7773 E = Modules.end(); I != E; ++I) {
78 ModuleProvider *MP = *I;
79 if (MP == P) {
74 Module *Found = *I;
75 if (Found == M) {
8076 Modules.erase(I);
81 clearGlobalMappingsFromModule(MP->getModule());
82 return MP->releaseModule(ErrInfo);
83 }
84 }
85 return NULL;
86 }
87
88 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
89 /// and deletes the ModuleProvider and owned Module. Avoids materializing
90 /// the underlying module.
91 void ExecutionEngine::deleteModuleProvider(ModuleProvider *P,
92 std::string *ErrInfo) {
93 for(SmallVector::iterator I = Modules.begin(),
94 E = Modules.end(); I != E; ++I) {
95 ModuleProvider *MP = *I;
96 if (MP == P) {
97 Modules.erase(I);
98 clearGlobalMappingsFromModule(MP->getModule());
99 delete MP;
100 return;
101 }
102 }
77 clearGlobalMappingsFromModule(M);
78 return true;
79 }
80 }
81 return false;
10382 }
10483
10584 /// FindFunctionNamed - Search all of the active modules to find the one that
10786 /// general code.
10887 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
10988 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
110 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
89 if (Function *F = Modules[i]->getFunction(FnName))
11190 return F;
11291 }
11392 return 0;
315294 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
316295 // Execute global ctors/dtors for each module in the program.
317296 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
318 runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
297 runStaticConstructorsDestructors(Modules[m], isDtors);
319298 }
320299
321300 #ifndef NDEBUG
392371 /// Interpreter or there's an error. If even an Interpreter cannot be created,
393372 /// NULL is returned.
394373 ///
395 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
374 ExecutionEngine *ExecutionEngine::create(Module *M,
396375 bool ForceInterpreter,
397376 std::string *ErrorStr,
398377 CodeGenOpt::Level OptLevel,
399378 bool GVsWithCode) {
400 return EngineBuilder(MP)
379 return EngineBuilder(M)
401380 .setEngineKind(ForceInterpreter
402381 ? EngineKind::Interpreter
403382 : EngineKind::JIT)
409388
410389 ExecutionEngine *ExecutionEngine::create(Module *M) {
411390 return EngineBuilder(M).create();
412 }
413
414 /// EngineBuilder - Overloaded constructor that automatically creates an
415 /// ExistingModuleProvider for an existing module.
416 EngineBuilder::EngineBuilder(Module *m) : MP(new ExistingModuleProvider(m)) {
417 InitEngine();
418391 }
419392
420393 ExecutionEngine *EngineBuilder::create() {
441414 if (WhichEngine & EngineKind::JIT) {
442415 if (ExecutionEngine::JITCtor) {
443416 ExecutionEngine *EE =
444 ExecutionEngine::JITCtor(MP, ErrorStr, JMM, OptLevel,
417 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
445418 AllocateGVsWithCode, CMModel);
446419 if (EE) return EE;
447420 }
451424 // an interpreter instead.
452425 if (WhichEngine & EngineKind::Interpreter) {
453426 if (ExecutionEngine::InterpCtor)
454 return ExecutionEngine::InterpCtor(MP, ErrorStr);
427 return ExecutionEngine::InterpCtor(M, ErrorStr);
455428 if (ErrorStr)
456429 *ErrorStr = "Interpreter has not been linked in.";
457430 return 0;
967940
968941 if (Modules.size() != 1) {
969942 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
970 Module &M = *Modules[m]->getModule();
943 Module &M = *Modules[m];
971944 for (Module::const_global_iterator I = M.global_begin(),
972945 E = M.global_end(); I != E; ++I) {
973946 const GlobalValue *GV = I;
1001974
1002975 std::vector NonCanonicalGlobals;
1003976 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1004 Module &M = *Modules[m]->getModule();
977 Module &M = *Modules[m];
1005978 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1006979 I != E; ++I) {
1007980 // In the multi-module case, see what this global maps to.
173173 }
174174
175175 void LLVMAddModuleProvider(LLVMExecutionEngineRef EE, LLVMModuleProviderRef MP){
176 unwrap(EE)->addModuleProvider(unwrap(MP));
176 unwrap(EE)->addModule(unwrap(MP));
177177 }
178178
179179 LLVMBool LLVMRemoveModuleProvider(LLVMExecutionEngineRef EE,
180180 LLVMModuleProviderRef MP,
181181 LLVMModuleRef *OutMod, char **OutError) {
182 std::string Error;
183 if (Module *Gone = unwrap(EE)->removeModuleProvider(unwrap(MP), &Error)) {
184 *OutMod = wrap(Gone);
185 return 0;
186 }
187 if (OutError)
188 *OutError = strdup(Error.c_str());
189 return 1;
182 Module *M = unwrap(MP);
183 unwrap(EE)->removeModule(M);
184 *OutMod = wrap(M);
185 return 0;
190186 }
191187
192188 LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
1616 #include "llvm/CodeGen/IntrinsicLowering.h"
1717 #include "llvm/DerivedTypes.h"
1818 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
2019 #include
2120 using namespace llvm;
2221
3231
3332 /// create - Create a new interpreter object. This can never fail.
3433 ///
35 ExecutionEngine *Interpreter::create(ModuleProvider *MP, std::string* ErrStr) {
36 // Tell this ModuleProvide to materialize and release the module
37 if (!MP->materializeModule(ErrStr))
34 ExecutionEngine *Interpreter::create(Module *M, std::string* ErrStr) {
35 // Tell this Module to materialize everything and release the GVMaterializer.
36 if (M->MaterializeAllPermanently(ErrStr))
3837 // We got an error, just return 0
3938 return 0;
4039
41 return new Interpreter(MP);
40 return new Interpreter(M);
4241 }
4342
4443 //===----------------------------------------------------------------------===//
4544 // Interpreter ctor - Initialize stuff
4645 //
47 Interpreter::Interpreter(ModuleProvider *M)
48 : ExecutionEngine(M), TD(M->getModule()) {
46 Interpreter::Interpreter(Module *M)
47 : ExecutionEngine(M), TD(M) {
4948
5049 memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
5150 setTargetData(&TD);
9393 std::vector AtExitHandlers;
9494
9595 public:
96 explicit Interpreter(ModuleProvider *M);
96 explicit Interpreter(Module *M);
9797 ~Interpreter();
9898
9999 /// runAtExitHandlers - Run any functions registered by the program's calls to
107107
108108 /// create - Create an interpreter ExecutionEngine. This can never fail.
109109 ///
110 static ExecutionEngine *create(ModuleProvider *M, std::string *ErrorStr = 0);
110 static ExecutionEngine *create(Module *M, std::string *ErrorStr = 0);
111111
112112 /// run - Start execution with the specified function and arguments.
113113 ///
1717 #include "llvm/Function.h"
1818 #include "llvm/GlobalVariable.h"
1919 #include "llvm/Instructions.h"
20 #include "llvm/ModuleProvider.h"
2120 #include "llvm/CodeGen/JITCodeEmitter.h"
2221 #include "llvm/CodeGen/MachineCodeInfo.h"
2322 #include "llvm/ExecutionEngine/GenericValue.h"
192191
193192 /// createJIT - This is the factory method for creating a JIT for the current
194193 /// machine, it does not fall back to the interpreter. This takes ownership
195 /// of the module provider.
196 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
194 /// of the module.
195 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
197196 std::string *ErrorStr,
198197 JITMemoryManager *JMM,
199198 CodeGenOpt::Level OptLevel,
200199 bool GVsWithCode,
201200 CodeModel::Model CMM) {
202 return JIT::createJIT(MP, ErrorStr, JMM, OptLevel, GVsWithCode, CMM);
203 }
204
205 ExecutionEngine *JIT::createJIT(ModuleProvider *MP,
201 return JIT::createJIT(M, ErrorStr, JMM, OptLevel, GVsWithCode, CMM);
202 }
203
204 ExecutionEngine *JIT::createJIT(Module *M,
206205 std::string *ErrorStr,
207206 JITMemoryManager *JMM,
208207 CodeGenOpt::Level OptLevel,
214213 return 0;
215214
216215 // Pick a target either via -march or by guessing the native arch.
217 TargetMachine *TM = JIT::selectTarget(MP, ErrorStr);
216 TargetMachine *TM = JIT::selectTarget(M, ErrorStr);
218217 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
219218 TM->setCodeModel(CMM);
220219
221220 // If the target supports JIT code generation, create a the JIT.
222221 if (TargetJITInfo *TJ = TM->getJITInfo()) {
223 return new JIT(MP, *TM, *TJ, JMM, OptLevel, GVsWithCode);
222 return new JIT(M, *TM, *TJ, JMM, OptLevel, GVsWithCode);
224223 } else {
225224 if (ErrorStr)
226225 *ErrorStr = "target does not support JIT code generation";
228227 }
229228 }
230229
231 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
230 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
232231 JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode)
233 : ExecutionEngine(MP), TM(tm), TJI(tji), AllocateGVsWithCode(GVsWithCode) {
232 : ExecutionEngine(M), TM(tm), TJI(tji), AllocateGVsWithCode(GVsWithCode) {
234233 setTargetData(TM.getTargetData());
235234
236 jitstate = new JITState(MP);
235 jitstate = new JITState(M);
237236
238237 // Initialize JCE
239238 JCE = createEmitter(*this, JMM, TM);
277276 delete &TM;
278277 }
279278
280 /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
281 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
282 /// ModuleProvider.
283 void JIT::addModuleProvider(ModuleProvider *MP) {
279 /// addModule - Add a new Module to the JIT. If we previously removed the last
280 /// Module, we need re-initialize jitstate with a valid Module.
281 void JIT::addModule(Module *M) {
284282 MutexGuard locked(lock);
285283
286284 if (Modules.empty()) {
287285 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
288286
289 jitstate = new JITState(MP);
287 jitstate = new JITState(M);
290288
291289 FunctionPassManager &PM = jitstate->getPM(locked);
292290 PM.add(new TargetData(*TM.getTargetData()));
301299 PM.doInitialization();
302300 }
303301
304 ExecutionEngine::addModuleProvider(MP);
305 }
306
307 /// removeModuleProvider - If we are removing the last ModuleProvider,
308 /// invalidate the jitstate since the PassManager it contains references a
309 /// released ModuleProvider.
310 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
311 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
312
313 MutexGuard locked(lock);
314
315 if (jitstate->getMP() == MP) {
302 ExecutionEngine::addModule(M);
303 }
304
305 /// removeModule - If we are removing the last Module, invalidate the jitstate
306 /// since the PassManager it contains references a released Module.
307 bool JIT::removeModule(Module *M) {
308 bool result = ExecutionEngine::removeModule(M);
309
310 MutexGuard locked(lock);
311
312 if (jitstate->getModule() == M) {
316313 delete jitstate;
317314 jitstate = 0;
318315 }
333330 PM.doInitialization();
334331 }
335332 return result;
336 }
337
338 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
339 /// and deletes the ModuleProvider and owned Module. Avoids materializing
340 /// the underlying module.
341 void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
342 ExecutionEngine::deleteModuleProvider(MP, E);
343
344 MutexGuard locked(lock);
345
346 if (jitstate->getMP() == MP) {
347 delete jitstate;
348 jitstate = 0;
349 }
350
351 if (!jitstate && !Modules.empty()) {
352 jitstate = new JITState(Modules[0]);
353
354 FunctionPassManager &PM = jitstate->getPM(locked);
355 PM.add(new TargetData(*TM.getTargetData()));
356
357 // Turn the machine code intermediate representation into bytes in memory
358 // that may be executed.
359 if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
360 llvm_report_error("Target does not support machine code emission!");
361 }
362
363 // Initialize passes.
364 PM.doInitialization();
365 }
366 }
367
368 /// materializeFunction - make sure the given function is fully read. If the
369 /// module is corrupt, this returns true and fills in the optional string with
370 /// information about the problem. If successful, this returns false.
371 bool JIT::materializeFunction(Function *F, std::string *ErrInfo) {
372 // Read in the function if it exists in this Module.
373 if (F->hasNotBeenReadFromBitcode()) {
374 // Determine the module provider this function is provided by.
375 Module *M = F->getParent();
376 ModuleProvider *MP = 0;
377 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
378 if (Modules[i]->getModule() == M) {
379 MP = Modules[i];
380 break;
381 }
382 }
383 if (MP)
384 return MP->materializeFunction(F, ErrInfo);
385
386 if (ErrInfo)
387 *ErrInfo = "Function isn't in a module we know about!";
388 return true;
389 }
390 // Succeed if the function is already read.
391 return false;
392333 }
393334
394335 /// run - Start execution with the specified function and arguments.
660601 // Now that this thread owns the lock, make sure we read in the function if it
661602 // exists in this Module.
662603 std::string ErrorMsg;
663 if (materializeFunction(F, &ErrorMsg)) {
604 if (F->Materialize(&ErrorMsg)) {
664605 llvm_report_error("Error reading function '" + F->getName()+
665606 "' from bitcode file: " + ErrorMsg);
666607 }
2929 class JITState {
3030 private:
3131 FunctionPassManager PM; // Passes to compile a function
32 ModuleProvider *MP; // ModuleProvider used to create the PM
32 Module *M; // Module used to create the PM
3333
3434 /// PendingFunctions - Functions which have not been code generated yet, but
3535 /// were called from a function being code generated.
3636 std::vector > PendingFunctions;
3737
3838 public:
39 explicit JITState(ModuleProvider *MP) : PM(MP), MP(MP) {}
39 explicit JITState(Module *M) : PM(M), M(M) {}
4040
4141 FunctionPassManager &getPM(const MutexGuard &L) {
4242 return PM;
4343 }
4444
45 ModuleProvider *getMP() const { return MP; }
45 Module *getModule() const { return M; }
4646 std::vector > &getPendingFunctions(const MutexGuard &L){
4747 return PendingFunctions;
4848 }
6262
6363 JITState *jitstate;
6464
65 JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
65 JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
6666 JITMemoryManager *JMM, CodeGenOpt::Level OptLevel,
6767 bool AllocateGVsWithCode);
6868 public:
7979 /// create - Create an return a new JIT compiler if there is one available
8080 /// for the current target. Otherwise, return null.
8181 ///
82 static ExecutionEngine *create(ModuleProvider *MP,
82 static ExecutionEngine *create(Module *M,
8383 std::string *Err,
8484 JITMemoryManager *JMM,
8585 CodeGenOpt::Level OptLevel =
8686 CodeGenOpt::Default,
8787 bool GVsWithCode = true,
8888 CodeModel::Model CMM = CodeModel::Default) {
89 return ExecutionEngine::createJIT(MP, Err, JMM, OptLevel, GVsWithCode,
89 return ExecutionEngine::createJIT(M, Err, JMM, OptLevel, GVsWithCode,
9090 CMM);
9191 }
9292
93 virtual void addModuleProvider(ModuleProvider *MP);
94
95 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
96 /// Relases the Module from the ModuleProvider, materializing it in the
97 /// process, and returns the materialized Module.
98 virtual Module *removeModuleProvider(ModuleProvider *MP,
99 std::string *ErrInfo = 0);
100
101 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
102 /// and deletes the ModuleProvider and owned Module. Avoids materializing
103 /// the underlying module.
104 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0);
105
106 /// materializeFunction - make sure the given function is fully read. If the
107 /// module is corrupt, this returns true and fills in the optional string with
108 /// information about the problem. If successful, this returns false.
109 ///
110 bool materializeFunction(Function *F, std::string *ErrInfo = 0);
93 virtual void addModule(Module *M);
94
95 /// removeModule - Remove a Module from the list of modules. Returns true if
96 /// M is found.
97 virtual bool removeModule(Module *M);
11198
11299 /// runFunction - Start execution with the specified function and arguments.
113100 ///
176163
177164 /// selectTarget - Pick a target either via -march or by guessing the native
178165 /// arch. Add any CPU features specified via -mcpu or -mattr.
179 static TargetMachine *selectTarget(ModuleProvider *MP, std::string *Err);
180
181 static ExecutionEngine *createJIT(ModuleProvider *MP,
166 static TargetMachine *selectTarget(Module *M, std::string *Err);
167
168 static ExecutionEngine *createJIT(Module *M,
182169 std::string *ErrorStr,
183170 JITMemoryManager *JMM,
184171 CodeGenOpt::Level OptLevel,
6262 // A declaration may stop being a declaration once it's fully read from bitcode.
6363 // This function returns true if F is fully read and is still a declaration.
6464 static bool isNonGhostDeclaration(const Function *F) {
65 return F->isDeclaration() && !F->hasNotBeenReadFromBitcode();
65 return F->isDeclaration() && !F->isMaterializable();
6666 }
6767
6868 //===----------------------------------------------------------------------===//
1414
1515 #include "JIT.h"
1616 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
1817 #include "llvm/ADT/Triple.h"
1918 #include "llvm/Support/CommandLine.h"
2019 #include "llvm/Support/raw_ostream.h"
4241
4342 /// selectTarget - Pick a target either via -march or by guessing the native
4443 /// arch. Add any CPU features specified via -mcpu or -mattr.
45 TargetMachine *JIT::selectTarget(ModuleProvider *MP, std::string *ErrorStr) {
46 Module &Mod = *MP->getModule();
47
48 Triple TheTriple(Mod.getTargetTriple());
44 TargetMachine *JIT::selectTarget(Module *Mod, std::string *ErrorStr) {
45 Triple TheTriple(Mod->getTargetTriple());
4946 if (TheTriple.getTriple().empty())
5047 TheTriple.setTriple(sys::getHostTriple());
5148
1313
1414 #include "llvm/Linker.h"
1515 #include "llvm/Module.h"
16 #include "llvm/ModuleProvider.h"
1716 #include "llvm/ADT/SetOperations.h"
1817 #include "llvm/Bitcode/Archive.h"
1918 #include "llvm/Config/config.h"
138137 do {
139138 CurrentlyUndefinedSymbols = UndefinedSymbols;
140139
141 // Find the modules we need to link into the target module
142 std::set Modules;
140 // Find the modules we need to link into the target module. Note that arch
141 // keeps ownership of these modules and may return the same Module* from a
142 // subsequent call.
143 std::set Modules;
143144 if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
144145 return error("Cannot find symbols in '" + Filename.str() +
145146 "': " + ErrMsg);
155156 NotDefinedByArchive.insert(UndefinedSymbols.begin(),
156157 UndefinedSymbols.end());
157158
158 // Loop over all the ModuleProviders that we got back from the archive
159 for (std::set::iterator I=Modules.begin(), E=Modules.end();
159 // Loop over all the Modules that we got back from the archive
160 for (std::set::iterator I=Modules.begin(), E=Modules.end();
160161 I != E; ++I) {
161162
162163 // Get the module we must link in.
163164 std::string moduleErrorMsg;
164 std::auto_ptr AutoModule((*I)->releaseModule( &moduleErrorMsg ));
165 if (!moduleErrorMsg.empty())
166 return error("Could not load a module: " + moduleErrorMsg);
165 Module* aModule = *I;
166 if (aModule != NULL) {
167 if (aModule->MaterializeAll(&moduleErrorMsg))
168 return error("Could not load a module: " + moduleErrorMsg);
167169
168 Module* aModule = AutoModule.get();
169
170 if (aModule != NULL) {
171170 verbose(" Linking in module: " + aModule->getModuleIdentifier());
172171
173172 // Link it in
121121 if (RelocM == Reloc::Static)
122122 return false;
123123
124 // GV with ghost linkage (in JIT lazy compilation mode) do not require an
125 // extra load from stub.
126 bool isDecl = GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode();
124 // Materializable GVs (in JIT lazy compilation mode) do not require an extra
125 // load from stub.
126 bool isDecl = GV->isDeclaration() && !GV->isMaterializable();
127127
128128 if (!isTargetDarwin()) {
129129 // Extra load is needed for all externally visible.
306306 Out << "GlobalValue::DLLExportLinkage"; break;
307307 case GlobalValue::ExternalWeakLinkage:
308308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::GhostLinkage:
310 Out << "GlobalValue::GhostLinkage"; break;
311309 case GlobalValue::CommonLinkage:
312310 Out << "GlobalValue::CommonLinkage"; break;
313311 }
129129 return false;
130130 // If symbol visibility is hidden, the extra load is not needed if
131131 // the symbol is definitely defined in the current translation unit.
132 bool isDecl = GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode();
132 bool isDecl = GV->isDeclaration() && !GV->isMaterializable();
133133 if (GV->hasHiddenVisibility() && !isDecl && !GV->hasCommonLinkage())
134134 return false;
135135 return GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
5252 if (GV->hasDLLImportLinkage())
5353 return X86II::MO_DLLIMPORT;
5454
55 // GV with ghost linkage (in JIT lazy compilation mode) do not require an
55 // Materializable GVs (in JIT lazy compilation mode) do not require an
5656 // extra load from stub.
57 bool isDecl = GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode();
57 bool isDecl = GV->isDeclaration() && !GV->isMaterializable();
5858
5959 // X86-64 in PIC mode.
6060 if (isPICStyleRIPRel()) {
149149 case GlobalValue::PrivateLinkage:
150150 case GlobalValue::LinkerPrivateLinkage:
151151 break;
152 case GlobalValue::GhostLinkage:
153 llvm_unreachable("Should not have any unmaterialized functions!");
154152 case GlobalValue::DLLImportLinkage:
155153 llvm_unreachable("DLLImport linkage is not supported by this target!");
156154 case GlobalValue::DLLExportLinkage:
466466 case GlobalValue::AppendingLinkage:
467467 case GlobalValue::DLLImportLinkage:
468468 case GlobalValue::DLLExportLinkage:
469 case GlobalValue::GhostLinkage:
470469 case GlobalValue::CommonLinkage:
471470 return ExternalStrong;
472471 }
14011401 case GlobalValue::AvailableExternallyLinkage:
14021402 Out << "available_externally ";
14031403 break;
1404 // This is invalid syntax and just a debugging aid.
1405 case GlobalValue::GhostLinkage: Out << "ghost "; break;
14061404 }
14071405 }
14081406
1919 #include "llvm/GlobalAlias.h"
2020 #include "llvm/LLVMContext.h"
2121 #include "llvm/TypeSymbolTable.h"
22 #include "llvm/ModuleProvider.h"
2322 #include "llvm/InlineAsm.h"
2423 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
2527 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
2829 #include
2930 #include
3031 #include
931932 return LLVMDLLExportLinkage;
932933 case GlobalValue::ExternalWeakLinkage:
933934 return LLVMExternalWeakLinkage;
934 case GlobalValue::GhostLinkage:
935 return LLVMGhostLinkage;
936935 case GlobalValue::CommonLinkage:
937936 return LLVMCommonLinkage;
938937 }
987986 GV->setLinkage(GlobalValue::ExternalWeakLinkage);
988987 break;
989988 case LLVMGhostLinkage:
990 GV->setLinkage(GlobalValue::GhostLinkage);
989 DEBUG(errs()
990 << "LLVMSetLinkage(): LLVMGhostLinkage is no longer supported.");
991991 break;
992992 case LLVMCommonLinkage:
993993 GV->setLinkage(GlobalValue::CommonLinkage);
19641964
19651965 LLVMModuleProviderRef
19661966 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M) {
1967 return wrap(new ExistingModuleProvider(unwrap(M)));
1967 return reinterpret_cast(M);
19681968 }
19691969
19701970 void LLVMDisposeModuleProvider(LLVMModuleProviderRef MP) {
0 //===-- GVMaterializer.cpp - Base implementation for GV materializers -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Minimal implementation of the abstract interface for materializing
10 // GlobalValues.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/GVMaterializer.h"
15 using namespace llvm;
16
17 GVMaterializer::~GVMaterializer() {}
4040
4141 const_cast(C)->destroyConstant();
4242 return true;
43 }
44
45 bool GlobalValue::isMaterializable() const {
46 return getParent()->isMaterializable(this);
47 }
48 bool GlobalValue::isDematerializable() const {
49 return getParent()->isDematerializable(this);
50 }
51 bool GlobalValue::Materialize(std::string *ErrInfo) {
52 return getParent()->Materialize(this, ErrInfo);
53 }
54 void GlobalValue::Dematerialize() {
55 getParent()->Dematerialize(this);
4356 }
4457
4558 /// removeDeadConstantUsers - If there are any dead constant users dangling
1414 #include "llvm/InstrTypes.h"
1515 #include "llvm/Constants.h"
1616 #include "llvm/DerivedTypes.h"
17 #include "llvm/GVMaterializer.h"
1718 #include "llvm/LLVMContext.h"
1819 #include "llvm/ADT/STLExtras.h"
1920 #include "llvm/ADT/StringExtras.h"
5556 //
5657
5758 Module::Module(StringRef MID, LLVMContext& C)
58 : Context(C), ModuleID(MID), DataLayout("") {
59 : Context(C), Materializer(NULL), ModuleID(MID), DataLayout("") {
5960 ValSymTab = new ValueSymbolTable();
6061 TypeSymTab = new TypeSymbolTable();
6162 NamedMDSymTab = new MDSymbolTable();
371372 }
372373
373374 //===----------------------------------------------------------------------===//
375 // Methods to control the materialization of GlobalValues in the Module.
376 //
377 void Module::setMaterializer(GVMaterializer *GVM) {
378 assert(!Materializer &&
379 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
380 " to clear it out before setting another one.");
381 Materializer.reset(GVM);
382 }
383
384 bool Module::isMaterializable(const GlobalValue *GV) const {
385 if (Materializer)
386 return Materializer->isMaterializable(GV);
387 return false;
388 }
389
390 bool Module::isDematerializable(const GlobalValue *GV) const {
391 if (Materializer)
392 return Materializer->isDematerializable(GV);
393 return false;
394 }
395
396 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
397 if (Materializer)
398 return Materializer->Materialize(GV, ErrInfo);
399 return false;
400 }
401
402 void Module::Dematerialize(GlobalValue *GV) {
403 if (Materializer)
404 return Materializer->Dematerialize(GV);
405 }
406
407 bool Module::MaterializeAll(std::string *ErrInfo) {
408 if (!Materializer)
409 return false;
410 return Materializer->MaterializeModule(this, ErrInfo);
411 }
412
413 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
414 if (MaterializeAll(ErrInfo))
415 return true;
416 Materializer.reset();
417 return false;
418 }
419
420 //===----------------------------------------------------------------------===//
374421 // Other module related stuff.
375422 //
376423
+0
-26
lib/VMCore/ModuleProvider.cpp less more
None //===-- ModuleProvider.cpp - Base implementation for module providers -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Minimal implementation of the abstract interface for providing a module.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/ModuleProvider.h"
14 #include "llvm/Module.h"
15 using namespace llvm;
16
17 /// ctor - always have a valid Module
18 ///
19 ModuleProvider::ModuleProvider() : TheModule(0) { }
20
21 /// dtor - when we leave, we take our Module with us
22 ///
23 ModuleProvider::~ModuleProvider() {
24 delete TheModule;
25 }
1515 #include "llvm/Pass.h"
1616 #include "llvm/PassManager.h"
1717 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
1918 #include "llvm/ADT/STLExtras.h"
2019 #include "llvm/ADT/StringMap.h"
2120 #include "llvm/Support/Debug.h"
1717 #include "llvm/Support/Debug.h"
1818 #include "llvm/Support/Timer.h"
1919 #include "llvm/Module.h"
20 #include "llvm/ModuleProvider.h"
2120 #include "llvm/Support/ErrorHandling.h"
2221 #include "llvm/Support/ManagedStatic.h"
2322 #include "llvm/Support/raw_ostream.h"
11931192 // FunctionPassManager implementation
11941193
11951194 /// Create new Function pass manager
1196 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1195 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
11971196 FPM = new FunctionPassManagerImpl(0);
11981197 // FPM is the top level manager.
11991198 FPM->setTopLevelManager(FPM);
12001199
12011200 AnalysisResolver *AR = new AnalysisResolver(*FPM);
12021201 FPM->setResolver(AR);
1203
1204 MP = P;
12051202 }
12061203
12071204 FunctionPassManager::~FunctionPassManager() {
12231220 ///
12241221 bool FunctionPassManager::run(Function &F) {
12251222 std::string errstr;
1226 if (MP->materializeFunction(&F, &errstr)) {
1223 if (F.Materialize(&errstr)) {
12271224 llvm_report_error("Error reading bitcode file: " + errstr);
12281225 }
12291226 return FPM->run(F);
12331230 /// doInitialization - Run all of the initializers for the function passes.
12341231 ///
12351232 bool FunctionPassManager::doInitialization() {
1236 return FPM->doInitialization(*MP->getModule());
1233 return FPM->doInitialization(*M);
12371234 }
12381235
12391236 /// doFinalization - Run all of the finalizers for the function passes.
12401237 ///
12411238 bool FunctionPassManager::doFinalization() {
1242 return FPM->doFinalization(*MP->getModule());
1239 return FPM->doFinalization(*M);
12431240 }
12441241
12451242 //===----------------------------------------------------------------------===//
4646 #include "llvm/IntrinsicInst.h"
4747 #include "llvm/Metadata.h"
4848 #include "llvm/Module.h"
49 #include "llvm/ModuleProvider.h"
5049 #include "llvm/Pass.h"
5150 #include "llvm/PassManager.h"
5251 #include "llvm/TypeSymbolTable.h"
412411
413412 void Verifier::visitGlobalValue(GlobalValue &GV) {
414413 Assert1(!GV.isDeclaration() ||
414 GV.isMaterializable() ||
415415 GV.hasExternalLinkage() ||
416416 GV.hasDLLImportLinkage() ||
417417 GV.hasExternalWeakLinkage() ||
418 GV.hasGhostLinkage() ||
419418 (isa(GV) &&
420419 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
421420 "Global is external, but doesn't have external or dllimport or weak linkage!",
647646 "Function takes metadata but isn't an intrinsic", I, &F);
648647 }
649648
650 if (F.isDeclaration()) {
649 if (F.isMaterializable()) {
650 // Function has a body somewhere we can't see.
651 } else if (F.isDeclaration()) {
651652 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
652 F.hasExternalWeakLinkage() || F.hasGhostLinkage(),
653 F.hasExternalWeakLinkage(),
653654 "invalid linkage type for function declaration", &F);
654655 } else {
655656 // Verify that this function (which has a body) is not named "llvm.*". It
19121913 Function &F = const_cast(f);
19131914 assert(!F.isDeclaration() && "Cannot verify external functions");
19141915
1915 ExistingModuleProvider MP(F.getParent());
1916 FunctionPassManager FPM(&MP);
1916 FunctionPassManager FPM(F.getParent());
19171917 Verifier *V = new Verifier(action);
19181918 FPM.add(V);
19191919 FPM.run(F);
1920 MP.releaseModule();
19211920 return V->Broken;
19221921 }
19231922
1414
1515 #include "llvm/LLVMContext.h"
1616 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
1817 #include "llvm/PassManager.h"
1918 #include "llvm/Pass.h"
2019 #include "llvm/ADT/Triple.h"
333332 PM.run(mod);
334333 } else {
335334 // Build up all of the passes that we want to do to the module.
336 ExistingModuleProvider Provider(M.release());
337 FunctionPassManager Passes(&Provider);
335 FunctionPassManager Passes(M.get());
338336
339337 // Add the target data from the target machine, if it exists, or the module.
340338 if (const TargetData *TD = Target.getTargetData())
1414
1515 #include "llvm/LLVMContext.h"
1616 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
1817 #include "llvm/Type.h"
1918 #include "llvm/Bitcode/ReaderWriter.h"
2019 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
109108
110109 // Load the bitcode...
111110 std::string ErrorMsg;
112 ModuleProvider *MP = NULL;
111 Module *Mod = NULL;
113112 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
114 MP = getBitcodeModuleProvider(Buffer, Context, &ErrorMsg);
115 if (!MP) delete Buffer;
116 }
117
118 if (!MP) {
113 Mod = getLazyBitcodeModule(Buffer, Context, &ErrorMsg);
114 if (!Mod) delete Buffer;
115 }
116
117 if (!Mod) {
119118 errs() << argv[0] << ": error loading program '" << InputFile << "': "
120119 << ErrorMsg << "\n";
121120 exit(1);
122121 }
123122
124 // Get the module as the MP could go away once EE takes over.
125 Module *Mod = NoLazyCompilation
126 ? MP->materializeModule(&ErrorMsg) : MP->getModule();
127 if (!Mod) {
128 errs() << argv[0] << ": bitcode didn't read correctly.\n";
129 errs() << "Reason: " << ErrorMsg << "\n";
130 exit(1);
131 }
132
133 EngineBuilder builder(MP);
123 // If not jitting lazily, load the whole bitcode file eagerly too.
124 if (NoLazyCompilation) {
125 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
126 errs() << argv[0] << ": bitcode didn't read correctly.\n";
127 errs() << "Reason: " << ErrorMsg << "\n";
128 exit(1);
129 }
130 }
131
132 EngineBuilder builder(Mod);
134133 builder.setErrorStr(&ErrorMsg);
135134 builder.setEngineKind(ForceInterpreter
136135 ? EngineKind::Interpreter
2020 #include "llvm/Linker.h"
2121 #include "llvm/LLVMContext.h"
2222 #include "llvm/Module.h"
23 #include "llvm/ModuleProvider.h"
2423 #include "llvm/PassManager.h"
2524 #include "llvm/ADT/StringExtras.h"
2625 #include "llvm/ADT/Triple.h"
391390 // Make sure everything is still good.
392391 passes.add(createVerifierPass());
393392
394 FunctionPassManager* codeGenPasses =
395 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
393 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
396394
397395 codeGenPasses->add(new TargetData(*_target->getTargetData()));
398396
1616 #include "llvm/Constants.h"
1717 #include "llvm/LLVMContext.h"
1818 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
2019 #include "llvm/ADT/OwningPtr.h"
2120 #include "llvm/ADT/Triple.h"
2221 #include "llvm/Bitcode/ReaderWriter.h"
6867 // takes ownership of buffer
6968 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
7069 {
71 OwningPtr mp(getBitcodeModuleProvider(buffer,
72 getGlobalContext()));
73 // on success, mp owns buffer and both are deleted at end of this method
74 if (!mp) {
70 OwningPtr m(getLazyBitcodeModule(buffer, getGlobalContext()));
71 // on success, m owns buffer and both are deleted at end of this method
72 if (!m) {
7573 delete buffer;
7674 return false;
7775 }
78 std::string actualTarget = mp->getModule()->getTargetTriple();
76 std::string actualTarget = m->getTargetTriple();
7977 return (strncmp(actualTarget.c_str(), triplePrefix,
8078 strlen(triplePrefix)) == 0);
8179 }
1313
1414 #include "llvm/LLVMContext.h"
1515 #include "llvm/Module.h"
16 #include "llvm/ModuleProvider.h"
1716 #include "llvm/PassManager.h"
1817 #include "llvm/CallGraphSCCPass.h"
1918 #include "llvm/Bitcode/ReaderWriter.h"
426425
427426 FunctionPassManager *FPasses = NULL;
428427 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
429 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
428 FPasses = new FunctionPassManager(M.get());
430429 if (TD)
431430 FPasses->add(new TargetData(*TD));
432431 }
1111 #include "llvm/LLVMContext.h"
1212 #include "llvm/Instructions.h"
1313 #include "llvm/Module.h"
14 #include "llvm/ModuleProvider.h"
1514 #include "llvm/ADT/OwningPtr.h"
1615 #include "llvm/CodeGen/MachineCodeInfo.h"
1716 #include "llvm/ExecutionEngine/JIT.h"
2222 #include "llvm/GlobalVariable.h"
2323 #include "llvm/LLVMContext.h"
2424 #include "llvm/Module.h"
25 #include "llvm/ModuleProvider.h"
2625 #include "llvm/Support/IRBuilder.h"
2726 #include "llvm/Support/MemoryBuffer.h"
2827 #include "llvm/Support/SourceMgr.h"
193192 protected:
194193 virtual void SetUp() {
195194 M = new Module("
", Context);
196 MP = new ExistingModuleProvider(M);
197195 RJMM = new RecordingJITMemoryManager;
198196 RJMM->setPoisonMemory(true);
199197 std::string Error;
200 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
198 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
201199 .setJITMemoryManager(RJMM)
202200 .setErrorStr(&Error).create());
203201 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
208206 }
209207
210208 LLVMContext Context;
211 Module *M; // Owned by MP.
212 ModuleProvider *MP; // Owned by ExecutionEngine.
209 Module *M; // Owned by ExecutionEngine.
213210 RecordingJITMemoryManager *RJMM;
214211 OwningPtr TheJIT;
215212 };
222219 TEST(JIT, GlobalInFunction) {
223220 LLVMContext context;
224221 Module *M = new Module("
", context);
225 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
226222
227223 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
228224 // Tell the memory manager to poison freed memory so that accessing freed
229225 // memory is more easily tested.
230226 MemMgr->setPoisonMemory(true);
231227 std::string Error;
232 OwningPtr JIT(EngineBuilder(MP)
228 OwningPtr JIT(EngineBuilder(M)
233229 .setEngineKind(EngineKind::JIT)
234230 .setErrorStr(&Error)
235231 .setJITMemoryManager(MemMgr)
427423 "} ");
428424 Function *func = M->getFunction("main");
429425 TheJIT->getPointerToFunction(func);
430 TheJIT->deleteModuleProvider(MP);
426 TheJIT->removeModule(M);
427 delete M;
431428
432429 SmallPtrSet FunctionsDeallocated;
433430 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
646643 }
647644
648645 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
649 // lazily. The associated ModuleProvider (owned by the ExecutionEngine) is
650 // returned in MP. Both will be NULL on an error. Bitcode must live at least
651 // as long as the ExecutionEngine.
646 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
647 // M. Both will be NULL on an error. Bitcode must live at least as long as the
648 // ExecutionEngine.
652649 ExecutionEngine *getJITFromBitcode(
653 LLVMContext &Context, const std::string &Bitcode, ModuleProvider *&MP) {
650 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
654651 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
655652 MemoryBuffer *BitcodeBuffer =
656653 MemoryBuffer::getMemBuffer(Bitcode.c_str(),
657654 Bitcode.c_str() + Bitcode.size(),
658655 "Bitcode for test");
659656 std::string errMsg;
660 MP = getBitcodeModuleProvider(BitcodeBuffer, Context, &errMsg);
661 if (MP == NULL) {
657 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
658 if (M == NULL) {
662659 ADD_FAILURE() << errMsg;
663660 delete BitcodeBuffer;
664661 return NULL;
665662 }
666 ExecutionEngine *TheJIT = EngineBuilder(MP)
663 ExecutionEngine *TheJIT = EngineBuilder(M)
667664 .setEngineKind(EngineKind::JIT)
668665 .setErrorStr(&errMsg)
669666 .create();
670667 if (TheJIT == NULL) {
671668 ADD_FAILURE() << errMsg;
672 delete MP;
673 MP = NULL;
669 delete M;
670 M = NULL;
674671 return NULL;
675672 }
676673 return TheJIT;
674 }
675
676 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
677 LLVMContext Context;
678 const std::string Bitcode =
679 AssembleToBitcode(Context,
680 "define available_externally i32 "
681 " @JITTest_AvailableExternallyFunction() { "
682 " ret i32 7 "
683 "} "
684 " "
685 "define i32 @func() { "
686 " %result = tail call i32 "
687 " @JITTest_AvailableExternallyFunction() "
688 " ret i32 %result "
689 "} ");
690 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
691 Module *M;
692 OwningPtr TheJIT(getJITFromBitcode(Context, Bitcode, M));
693 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
694 TheJIT->DisableLazyCompilation(true);
695
696 Function *funcIR = M->getFunction("func");
697 Function *availableFunctionIR =
698 M->getFunction("JITTest_AvailableExternallyFunction");
699
700 // Double-check that the available_externally function is still unmaterialized
701 // when getPointerToFunction needs to find out if it's available_externally.
702 EXPECT_TRUE(availableFunctionIR->isMaterializable());
703
704 int32_t (*func)() = reinterpret_cast(
705 (intptr_t)TheJIT->getPointerToFunction(funcIR));
706 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
707 << " not 7 from the IR version.";
677708 }
678709
679710 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
696727 " ret i32 %result "
697728 "} ");
698729 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
699 ModuleProvider *MP;
700 OwningPtr TheJIT(getJITFromBitcode(Context, Bitcode, MP));
730 Module *M;
731 OwningPtr TheJIT(getJITFromBitcode(Context, Bitcode, M));
701732 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
702733 TheJIT->DisableLazyCompilation(true);
703734
704 Module *M = MP->getModule();
705735 Function *recur1IR = M->getFunction("recur1");
706736 Function *recur2IR = M->getFunction("recur2");
707 EXPECT_TRUE(recur1IR->hasNotBeenReadFromBitcode());
708 EXPECT_TRUE(recur2IR->hasNotBeenReadFromBitcode());
737 EXPECT_TRUE(recur1IR->isMaterializable());
738 EXPECT_TRUE(recur2IR->isMaterializable());
709739
710740 int32_t (*recur1)(int32_t) = reinterpret_cast(
711741 (intptr_t)TheJIT->getPointerToFunction(recur1IR));