llvm.org GIT mirror llvm / 8b477ed
Add a pointer to the owning LLVMContext to Module. This requires threading LLVMContext through a lot of the bitcode reader and ASM parser APIs, as well as supporting it in all of the tools. Patches for Clang and LLVM-GCC to follow. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@74614 91177308-0d34-0410-b5e6-96231b3b80d8 Owen Anderson 10 years ago
60 changed file(s) with 278 addition(s) and 147 deletion(s). Raw diff Collapse all Expand all
3535 const char *BrainF::label = "brainf";
3636 const char *BrainF::testreg = "test";
3737
38 Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf) {
38 Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
39 LLVMContext* Context) {
3940 in = in1;
4041 memtotal = mem;
4142 comflag = cf;
4243
43 header();
44 header(Context);
4445 readloop(0, 0, 0);
4546 delete builder;
4647 return module;
4748 }
4849
49 void BrainF::header() {
50 module = new Module("BrainF");
50 void BrainF::header(LLVMContext* C) {
51 module = new Module("BrainF", C);
5152
5253 //Function prototypes
5354
1414 #ifndef BRAINF_H
1515 #define BRAINF_H
1616
17 #include "llvm/LLVMContext.h"
1718 #include "llvm/Module.h"
1819 #include "llvm/Support/IRBuilder.h"
1920
3738 /// containing the resulting code.
3839 /// On error, it calls abort.
3940 /// The caller must delete the returned module.
40 Module *parse(std::istream *in1, int mem, CompileFlags cf);
41 Module *parse(std::istream *in1, int mem, CompileFlags cf, LLVMContext* C);
4142
4243 protected:
4344 /// The different symbols in the BrainF language
6364 static const char *testreg;
6465
6566 /// Put the brainf function preamble and other fixed pieces of code
66 void header();
67 void header(LLVMContext* C);
6768
6869 /// The main loop for parsing. It calls itself recursively
6970 /// to handle the depth of nesting of "[]".
8585 int main(int argc, char **argv) {
8686 cl::ParseCommandLineOptions(argc, argv, " BrainF compiler\n");
8787
88 LLVMContext Context;
89
8890 if (InputFilename == "") {
8991 std::cerr<<"Error: You must specify the filename of the program to "
9092 "be compiled. Use --help to see the options.\n";
123125
124126 //Read the BrainF program
125127 BrainF bf;
126 Module *mod = bf.parse(in, 65536, cf); //64 KiB
128 Module *mod = bf.parse(in, 65536, cf, &Context); //64 KiB
127129 if (in != &std::cin) {delete in;}
128130 addMainFunction(mod);
129131
2222 //
2323 //===----------------------------------------------------------------------===//
2424
25 #include "llvm/LLVMContext.h"
2526 #include "llvm/Module.h"
2627 #include "llvm/DerivedTypes.h"
2728 #include "llvm/Constants.h"
8990 int main(int argc, char **argv) {
9091 int n = argc > 1 ? atol(argv[1]) : 24;
9192
93 LLVMContext Context;
94
9295 // Create some module to put our function into it.
93 Module *M = new Module("test");
96 Module *M = new Module("test", &Context);
9497
9598 // We are about to create the "fib" function:
9699 Function *FibF = CreateFibFunction(M);
3333 //
3434 //===----------------------------------------------------------------------===//
3535
36 #include "llvm/LLVMContext.h"
3637 #include "llvm/Module.h"
3738 #include "llvm/Constants.h"
3839 #include "llvm/DerivedTypes.h"
4950 int main() {
5051
5152 InitializeNativeTarget();
53
54 LLVMContext Context;
5255
5356 // Create some module to put our function into it.
54 Module *M = new Module("test");
57 Module *M = new Module("test", &Context);
5558
5659 // Create the add1 function entry and insert this entry into module M. The
5760 // function will have a return type of "int" and take an argument of "int".
0 #include "llvm/DerivedTypes.h"
11 #include "llvm/ExecutionEngine/ExecutionEngine.h"
2 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
34 #include "llvm/ModuleProvider.h"
45 #include "llvm/PassManager.h"
10821083
10831084 int main() {
10841085 InitializeNativeTarget();
1086 LLVMContext Context;
10851087
10861088 // Install standard binary operators.
10871089 // 1 is lowest precedence.
10961098 getNextToken();
10971099
10981100 // Make the module, which holds all the code.
1099 TheModule = new Module("my cool jit");
1101 TheModule = new Module("my cool jit", &Context);
11001102
11011103 // Create the JIT.
11021104 TheExecutionEngine = ExecutionEngine::create(TheModule);
1212 //
1313 //===----------------------------------------------------------------------===//
1414
15 #include "llvm/LLVMContext.h"
1516 #include "llvm/Module.h"
1617 #include "llvm/DerivedTypes.h"
1718 #include "llvm/Constants.h"
2122 using namespace llvm;
2223
2324 int main() {
25 LLVMContext Context;
26
2427 // Create the "module" or "program" or "translation unit" to hold the
2528 // function
26 Module *M = new Module("test");
29 Module *M = new Module("test", &Context);
2730
2831 // Create the main function: first create the type 'int ()'
2932 FunctionType *FT = FunctionType::get(Type::Int32Ty, /*not vararg*/false);
1717 // same time). This test had assertion errors until I got the locking right.
1818
1919 #include
20 #include "llvm/LLVMContext.h"
2021 #include "llvm/Module.h"
2122 #include "llvm/Constants.h"
2223 #include "llvm/DerivedTypes.h"
231232
232233 int main() {
233234 InitializeNativeTarget();
235 LLVMContext Context;
234236
235237 // Create some module to put our function into it.
236 Module *M = new Module("test");
238 Module *M = new Module("test", &Context);
237239
238240 Function* add1F = createAdd1( M );
239241 Function* fibF = CreateFibFunction( M );
2020 class Module;
2121 class ParseError;
2222 class raw_ostream;
23 class LLVMContext;
2324
2425 /// This function is the main interface to the LLVM Assembly Parser. It parses
2526 /// an ASCII file that (presumably) contains LLVM Assembly code. It returns a
2930 /// @brief Parse LLVM Assembly from a file
3031 Module *ParseAssemblyFile(
3132 const std::string &Filename, ///< The name of the file to parse
32 ParseError &Error ///< If not null, an object to return errors in.
33 ParseError &Error, ///< If not null, an object to return errors in.
34 LLVMContext* Context ///< Context in which to allocate globals info.
3335 );
3436
3537 /// The function is a secondary interface to the LLVM Assembly Parser. It parses
4143 Module *ParseAssemblyString(
4244 const char *AsmString, ///< The string containing assembly
4345 Module *M, ///< A module to add the assembly too.
44 ParseError &Error ///< If not null, an object to return errors in.
46 ParseError &Error, ///< If not null, an object to return errors in.
47 LLVMContext* Context
4548 );
4649
4750 //===------------------------------------------------------------------------===
3131 class Module; // From VMCore
3232 class Archive; // Declared below
3333 class ArchiveMemberHeader; // Internal implementation class
34 class LLVMContext; // Global data
3435
3536 /// This class is the main class manipulated by users of the Archive class. It
3637 /// holds information about one member of the Archive. It is also the element
277278 /// @returns An Archive* that represents the new archive file.
278279 /// @brief Create an empty Archive.
279280 static Archive* CreateEmpty(
280 const sys::Path& Filename ///< Name of the archive to (eventually) create.
281 const sys::Path& Filename,///< Name of the archive to (eventually) create.
282 LLVMContext* C ///< Context to use for global information
281283 );
282284
283285 /// Open an existing archive and load its contents in preparation for
288290 /// @brief Open and load an archive file
289291 static Archive* OpenAndLoad(
290292 const sys::Path& filePath, ///< The file path to open and load
293 LLVMContext* C, ///< The context to use for global information
291294 std::string* ErrorMessage ///< An optional error string
292295 );
293296
309312 /// @brief Open an existing archive and load its symbols.
310313 static Archive* OpenAndLoadSymbols(
311314 const sys::Path& Filename, ///< Name of the archive file to open
315 LLVMContext* C, ///< The context to use for global info
312316 std::string* ErrorMessage=0 ///< An optional error string
313317 );
314318
448452 protected:
449453 /// @brief Construct an Archive for \p filename and optionally map it
450454 /// into memory.
451 explicit Archive(const sys::Path& filename);
455 explicit Archive(const sys::Path& filename, LLVMContext* C);
452456
453457 /// @param data The symbol table data to be parsed
454458 /// @param len The length of the symbol table data
529533 unsigned firstFileOffset; ///< Offset to first normal file.
530534 ModuleMap modules; ///< The modules loaded via symbol lookup.
531535 ArchiveMember* foreignST; ///< This holds the foreign symbol table.
536 LLVMContext* Context; ///< This holds global data.
532537 /// @}
533538 /// @name Hidden
534539 /// @{
2222 class MemoryBuffer;
2323 class ModulePass;
2424 class BitstreamWriter;
25 class LLVMContext;
2526 class raw_ostream;
2627
2728 /// getBitcodeModuleProvider - Read the header of the specified bitcode buffer
3031 /// error, this returns null, *does not* take ownership of Buffer, and fills
3132 /// in *ErrMsg with an error description if ErrMsg is non-null.
3233 ModuleProvider *getBitcodeModuleProvider(MemoryBuffer *Buffer,
34 LLVMContext* Context,
3335 std::string *ErrMsg = 0);
3436
3537 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3638 /// If an error occurs, this returns null and fills in *ErrMsg if it is
3739 /// non-null. This method *never* takes ownership of Buffer.
38 Module *ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg = 0);
40 Module *ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext* Context,
41 std::string *ErrMsg = 0);
3942
4043 /// WriteBitcodeToFile - Write the specified module to the specified output
4144 /// stream.
1919 namespace llvm {
2020 class Module;
2121 class InferiorProcess;
22 class LLVMContext;
2223
2324 /// Debugger class - This class implements the LLVM source-level debugger.
2425 /// This allows clients to handle the user IO processing without having to
9495 /// the PATH for the specified program, loading it when found. If the
9596 /// specified program cannot be found, an exception is thrown to indicate
9697 /// the error.
97 void loadProgram(const std::string &Path);
98 void loadProgram(const std::string &Path, LLVMContext* Context);
9899
99100 /// unloadProgram - If a program is running, kill it, then unload all traces
100101 /// of the current program. If no program is loaded, this method silently
4343 // to know that getenv() never returns -1, this will do the job.
4444 if (std::getenv("bar") != (char*) -1)
4545 return;
46 llvm::Module* M = new llvm::Module("");
46 llvm::Module* M = new llvm::Module("", 0);
4747 (void)new llvm::UnreachableInst();
4848 (void) llvm::createVerifierPass();
4949 (void) new llvm::Mangler(*M,"");
2020 namespace llvm {
2121
2222 class Module;
23 class LLVMContext;
2324
2425 /// This class provides the core functionality of linking in LLVM. It retains a
2526 /// Module object which is the composite of the modules and libraries linked
6566 Linker(
6667 const std::string& progname, ///< name of tool running linker
6768 const std::string& modulename, ///< name of linker's end-result module
69 LLVMContext* C, ///< Context for global info
6870 unsigned Flags = 0 ///< ControlFlags (one or more |'d together)
6971 );
7072
282284 /// @name Data
283285 /// @{
284286 private:
287 LLVMContext* Context; ///< The context for global information
285288 Module* Composite; ///< The composite module linked together
286289 std::vector LibPaths; ///< The library search paths
287290 unsigned Flags; ///< Flags to control optional behavior.
2424
2525 class GlobalValueRefMap; // Used by ConstantVals.cpp
2626 class FunctionType;
27 class LLVMContext;
2728
2829 template<> struct ilist_traits
2930 : public SymbolTableListTraits {
108109 /// @name Member Variables
109110 /// @{
110111 private:
112 LLVMContext* Context; ///< The LLVMContext from which types and
113 ///< constants are allocated.
111114 GlobalListType GlobalList; ///< The Global Variables in the module
112115 FunctionListType FunctionList; ///< The Functions in the module
113116 AliasListType AliasList; ///< The Aliases in the module
127130 public:
128131 /// The Module constructor. Note that there is no default constructor. You
129132 /// must provide a name for the module upon construction.
130 explicit Module(const std::string &ModuleID);
133 explicit Module(const std::string &ModuleID, LLVMContext* C);
131134 /// The module destructor. This will dropAllReferences.
132135 ~Module();
133136
155158 /// Get the target pointer size.
156159 /// @returns PointerSize - an enumeration for the size of the target's pointer
157160 PointerSize getPointerSize() const;
161
162 /// Get the global data context.
163 /// @returns LLVMContext - a container for LLVM's global information
164 LLVMContext* getContext() const { return Context; }
158165
159166 /// Get any module-scope inline assembly blocks.
160167 /// @returns a string containing the module-scope inline assembly blocks.
3636 class CallGraph;
3737 class TargetData;
3838 class LoopInfo;
39 class LLVMContext;
3940 template class LoopBase;
4041 typedef LoopBase Loop;
4142
2828 /* Builds a module from the bitcode in the specified memory buffer, returning a
2929 reference to the module via the OutModule parameter. Returns 0 on success.
3030 Optionally returns a human-readable error message via OutMessage. */
31 int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf,
31 int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMContextRef ContextRef,
3232 LLVMModuleRef *OutModule, char **OutMessage);
3333
3434 /* Reads a module from the specified path, returning via the OutMP parameter
3535 a module provider which performs lazy deserialization. Returns 0 on success.
3636 Optionally returns a human-readable error message via OutMessage. */
3737 int LLVMGetBitcodeModuleProvider(LLVMMemoryBufferRef MemBuf,
38 LLVMContextRef ContextRef,
3839 LLVMModuleProviderRef *OutMP,
3940 char **OutMessage);
4041
4646 /* Opaque types. */
4747
4848 /**
49 * The top-level container for all LLVM global data. See the LLVMContext class.
50 */
51 typedef struct LLVMCtxt *LLVMContextRef;
52
53 /**
4954 * The top-level container for all other LLVM Intermediate Representation (IR)
5055 * objects. See the llvm::Module class.
5156 */
186191
187192
188193 /*===-- Modules -----------------------------------------------------------===*/
194
195 /* Create and destroy contexts. */
196 LLVMContextRef LLVMContextCreate();
197 void LLVMContextDispose(LLVMContextRef C);
189198
190199 /* Create and destroy modules. */
191200 /** See llvm::Module::Module. */
814823 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(PATypeHolder, LLVMTypeHandleRef )
815824 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ModuleProvider, LLVMModuleProviderRef)
816825 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer, LLVMMemoryBufferRef )
826 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef )
817827 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBase, LLVMPassManagerRef )
818828
819829 #undef DEFINE_STDCXX_CONVERSION_FUNCTIONS
137137 // Archive constructor - this is the only constructor that gets used for the
138138 // Archive class. Everything else (default,copy) is deprecated. This just
139139 // initializes and maps the file into memory, if requested.
140 Archive::Archive(const sys::Path& filename)
140 Archive::Archive(const sys::Path& filename, LLVMContext* C)
141141 : archPath(filename), members(), mapfile(0), base(0), symTab(), strtab(),
142 symTabSize(0), firstFileOffset(0), modules(), foreignST(0) {
142 symTabSize(0), firstFileOffset(0), modules(), foreignST(0), Context(C) {
143143 }
144144
145145 bool
207207
208208 // Get just the externally visible defined symbols from the bitcode
209209 bool llvm::GetBitcodeSymbols(const sys::Path& fName,
210 LLVMContext* Context,
210211 std::vector& symbols,
211212 std::string* ErrMsg) {
212213 std::auto_ptr Buffer(
216217 return true;
217218 }
218219
219 ModuleProvider *MP = getBitcodeModuleProvider(Buffer.get(), ErrMsg);
220 ModuleProvider *MP = getBitcodeModuleProvider(Buffer.get(), Context, ErrMsg);
220221 if (!MP)
221222 return true;
222223
238239 ModuleProvider*
239240 llvm::GetBitcodeSymbols(const unsigned char *BufPtr, unsigned Length,
240241 const std::string& ModuleID,
242 LLVMContext* Context,
241243 std::vector& symbols,
242244 std::string* ErrMsg) {
243245 // Get the module provider
244246 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(Length, ModuleID.c_str());
245247 memcpy((char*)Buffer->getBufferStart(), BufPtr, Length);
246248
247 ModuleProvider *MP = getBitcodeModuleProvider(Buffer, ErrMsg);
249 ModuleProvider *MP = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
248250 if (!MP)
249251 return 0;
250252
2929 #define ARFILE_MEMBER_MAGIC "`\n" ///< fmag field magic #
3030
3131 namespace llvm {
32
33 class LLVMContext;
3234
3335 /// The ArchiveMemberHeader structure is used internally for bitcode
3436 /// archives.
7072
7173 // Get just the externally visible defined symbols from the bitcode
7274 bool GetBitcodeSymbols(const sys::Path& fName,
75 LLVMContext* Context,
7376 std::vector& symbols,
7477 std::string* ErrMsg);
7578
7679 ModuleProvider* GetBitcodeSymbols(const unsigned char*Buffer,unsigned Length,
7780 const std::string& ModuleID,
81 LLVMContext* Context,
7882 std::vector& symbols,
7983 std::string* ErrMsg);
8084 }
326326
327327 // Open and completely load the archive file.
328328 Archive*
329 Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage)
330 {
331 std::auto_ptr result ( new Archive(file));
329 Archive::OpenAndLoad(const sys::Path& file, LLVMContext* C,
330 std::string* ErrorMessage) {
331 std::auto_ptr result ( new Archive(file, C));
332332 if (result->mapToMemory(ErrorMessage))
333333 return 0;
334334 if (!result->loadArchive(ErrorMessage))
338338
339339 // Get all the bitcode modules from the archive
340340 bool
341 Archive::getAllModules(std::vector& Modules, std::string* ErrMessage) {
341 Archive::getAllModules(std::vector& Modules,
342 std::string* ErrMessage) {
342343
343344 for (iterator I=begin(), E=end(); I != E; ++I) {
344345 if (I->isBitcode()) {
348349 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
349350 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
350351
351 Module *M = ParseBitcodeFile(Buffer, ErrMessage);
352 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
352353 delete Buffer;
353354 if (!M)
354355 return true;
439440 }
440441
441442 // Open the archive and load just the symbol tables
442 Archive*
443 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
444 std::auto_ptr result ( new Archive(file) );
443 Archive* Archive::OpenAndLoadSymbols(const sys::Path& file, LLVMContext* C,
444 std::string* ErrorMessage) {
445 std::auto_ptr result ( new Archive(file, C) );
445446 if (result->mapToMemory(ErrorMessage))
446447 return 0;
447448 if (!result->loadSymbolTable(ErrorMessage))
487488 FullMemberName.c_str());
488489 memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
489490
490 ModuleProvider *mp = getBitcodeModuleProvider(Buffer, ErrMsg);
491 ModuleProvider *mp = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
491492 if (!mp)
492493 return 0;
493494
535536 mbr->getPath().toString() + ")";
536537 ModuleProvider* MP =
537538 GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(),
538 FullMemberName, symbols, error);
539 FullMemberName, Context, symbols, error);
539540
540541 if (MP) {
541542 // Insert the module's symbols into the symbol table
614615 MemoryBuffer *Buffer =
615616 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
616617 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
617 Module *M = ParseBitcodeFile(Buffer);
618 Module *M = ParseBitcodeFile(Buffer, Context);
618619 delete Buffer;
619620 if (!M)
620621 return false; // Couldn't parse bitcode, not a bitcode archive.
6363 }
6464
6565 // Create an empty archive.
66 Archive*
67 Archive::CreateEmpty(const sys::Path& FilePath ) {
68 Archive* result = new Archive(FilePath);
66 Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext* C) {
67 Archive* result = new Archive(FilePath, C);
6968 return result;
7069 }
7170
228227 + ")";
229228 ModuleProvider* MP =
230229 GetBitcodeSymbols((const unsigned char*)data,fSize,
231 FullMemberName, symbols, ErrMsg);
230 FullMemberName, Context, symbols, ErrMsg);
232231
233232 // If the bitcode parsed successfully
234233 if ( MP ) {
1919 #include
2020 using namespace llvm;
2121
22 Module *llvm::ParseAssemblyFile(const std::string &Filename, ParseError &Err) {
22 Module *llvm::ParseAssemblyFile(const std::string &Filename, ParseError &Err,
23 LLVMContext* Context) {
2324 Err.setFilename(Filename);
2425
2526 std::string ErrorStr;
3031 return 0;
3132 }
3233
33 OwningPtr M(new Module(Filename));
34 OwningPtr M(new Module(Filename, Context));
3435 if (LLParser(F.get(), Err, M.get()).Run())
3536 return 0;
3637 return M.take();
3738 }
3839
3940 Module *llvm::ParseAssemblyString(const char *AsmString, Module *M,
40 ParseError &Err) {
41 ParseError &Err, LLVMContext* Context) {
4142 Err.setFilename("");
4243
4344 OwningPtr
4950 return LLParser(F.get(), Err, M).Run() ? 0 : M;
5051
5152 // Otherwise create a new module.
52 OwningPtr M2(new Module(""));
53 OwningPtr M2(new Module("", Context));
5354 if (LLParser(F.get(), Err, M2.get()).Run())
5455 return 0;
5556 return M2.take();
1717 /* Builds a module from the bitcode in the specified memory buffer, returning a
1818 reference to the module via the OutModule parameter. Returns 0 on success.
1919 Optionally returns a human-readable error message via OutMessage. */
20 int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf,
20 int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMContextRef ContextRef,
2121 LLVMModuleRef *OutModule, char **OutMessage) {
2222 std::string Message;
2323
24 *OutModule = wrap(ParseBitcodeFile(unwrap(MemBuf), &Message));
24 *OutModule = wrap(ParseBitcodeFile(unwrap(MemBuf), unwrap(ContextRef),
25 &Message));
2526 if (!*OutModule) {
2627 if (OutMessage)
2728 *OutMessage = strdup(Message.c_str());
3536 a module provider which performs lazy deserialization. Returns 0 on success.
3637 Optionally returns a human-readable error message via OutMessage. */
3738 int LLVMGetBitcodeModuleProvider(LLVMMemoryBufferRef MemBuf,
39 LLVMContextRef ContextRef,
3840 LLVMModuleProviderRef *OutMP,
3941 char **OutMessage) {
4042 std::string Message;
4143
42 *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), &Message));
44 *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), unwrap(ContextRef),
45 &Message));
4346 if (!*OutMP) {
4447 if (OutMessage)
4548 *OutMessage = strdup(Message.c_str());
10861086 return Error("Malformed block record");
10871087
10881088 // Otherwise, create the module.
1089 TheModule = new Module(ModuleID);
1089 TheModule = new Module(ModuleID, Context);
10901090
10911091 SmallVector Record;
10921092 std::vector SectionTable;
20892089 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
20902090 ///
20912091 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2092 LLVMContext* Context,
20922093 std::string *ErrMsg) {
2093 BitcodeReader *R = new BitcodeReader(Buffer);
2094 BitcodeReader *R = new BitcodeReader(Buffer, Context);
20942095 if (R->ParseBitcode()) {
20952096 if (ErrMsg)
20962097 *ErrMsg = R->getErrorString();
21052106
21062107 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
21072108 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2108 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2109 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext* Context,
2110 std::string *ErrMsg){
21092111 BitcodeReader *R;
2110 R = static_cast(getBitcodeModuleProvider(Buffer, ErrMsg));
2112 R = static_cast(getBitcodeModuleProvider(Buffer, Context,
2113 ErrMsg));
21112114 if (!R) return 0;
21122115
21132116 // Read in the entire module.
2525
2626 namespace llvm {
2727 class MemoryBuffer;
28 class LLVMContext;
2829
2930 //===----------------------------------------------------------------------===//
3031 // BitcodeReaderValueList Class
8485 };
8586
8687 class BitcodeReader : public ModuleProvider {
88 LLVMContext* Context;
8789 MemoryBuffer *Buffer;
8890 BitstreamReader StreamFile;
8991 BitstreamCursor Stream;
122124 /// stream) and what linkage the original function had.
123125 DenseMap > DeferredFunctionInfo;
124126 public:
125 explicit BitcodeReader(MemoryBuffer *buffer)
126 : Buffer(buffer), ErrorString(0) {
127 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext* C)
128 : Context(C), Buffer(buffer), ErrorString(0) {
127129 HasReversedFunctionsWithBodies = false;
128130 }
129131 ~BitcodeReader() {
4545 }
4646
4747 static Module *
48 getMaterializedModuleProvider(const std::string &Filename) {
48 getMaterializedModuleProvider(const std::string &Filename, LLVMContext* C) {
4949 std::auto_ptr Buffer;
5050 Buffer.reset(MemoryBuffer::getFileOrSTDIN(Filename.c_str()));
5151 if (Buffer.get())
52 return ParseBitcodeFile(Buffer.get());
52 return ParseBitcodeFile(Buffer.get(), C);
5353 return 0;
5454 }
5555
5757 /// the PATH for the specified program, loading it when found. If the
5858 /// specified program cannot be found, an exception is thrown to indicate the
5959 /// error.
60 void Debugger::loadProgram(const std::string &Filename) {
61 if ((Program = getMaterializedModuleProvider(Filename)) ||
62 (Program = getMaterializedModuleProvider(Filename+".bc")))
60 void Debugger::loadProgram(const std::string &Filename, LLVMContext* C) {
61 if ((Program = getMaterializedModuleProvider(Filename, C)) ||
62 (Program = getMaterializedModuleProvider(Filename+".bc", C)))
6363 return; // Successfully loaded the program.
6464
6565 // Search the program path for the file...
6868
6969 std::string Directory = getToken(Path, ":");
7070 while (!Directory.empty()) {
71 if ((Program = getMaterializedModuleProvider(Directory +"/"+ Filename)) ||
72 (Program = getMaterializedModuleProvider(Directory +"/"+ Filename
73 + ".bc")))
71 if ((Program = getMaterializedModuleProvider(Directory +"/"+ Filename, C))
72 || (Program = getMaterializedModuleProvider(Directory +"/"+ Filename
73 + ".bc", C)))
7474 return; // Successfully loaded the program.
7575
7676 Directory = getToken(Path, ":");
114114
115115 std::string ErrMsg;
116116 std::auto_ptr AutoArch (
117 Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
117 Archive::OpenAndLoadSymbols(Filename, Context, &ErrMsg));
118118
119119 Archive* arch = AutoArch.get();
120120
159159 if (File.toString() == "-") {
160160 std::auto_ptr M;
161161 if (MemoryBuffer *Buffer = MemoryBuffer::getSTDIN()) {
162 M.reset(ParseBitcodeFile(Buffer, &Error));
162 M.reset(ParseBitcodeFile(Buffer, Context, &Error));
163163 delete Buffer;
164164 if (M.get())
165165 if (!LinkInModule(M.get(), &Error))
1919 using namespace llvm;
2020
2121 Linker::Linker(const std::string& progname, const std::string& modname,
22 unsigned flags)
23 : Composite(0)
24 , LibPaths()
25 , Flags(flags)
26 , Error()
27 , ProgramName(progname)
28 {
29 Composite = new Module(modname);
30 }
22 LLVMContext* C, unsigned flags):
23 Context(C),
24 Composite(new Module(modname, C)),
25 LibPaths(),
26 Flags(flags),
27 Error(),
28 ProgramName(progname) { }
3129
32 Linker::Linker(const std::string& progname, Module* aModule, unsigned flags)
33 : Composite(aModule)
34 , LibPaths()
35 , Flags(flags)
36 , Error()
37 , ProgramName(progname)
38 {
39 }
30 Linker::Linker(const std::string& progname, Module* aModule, unsigned flags) :
31 Context(aModule->getContext()),
32 Composite(aModule),
33 LibPaths(),
34 Flags(flags),
35 Error(),
36 ProgramName(progname) { }
4037
4138 Linker::~Linker() {
4239 delete Composite;
105102 const std::string &FNS = FN.toString();
106103 std::auto_ptr Buffer(MemoryBuffer::getFileOrSTDIN(FNS.c_str()));
107104 if (Buffer.get())
108 Result = ParseBitcodeFile(Buffer.get(), &ParseErrorMessage);
105 Result = ParseBitcodeFile(Buffer.get(), Context, &ParseErrorMessage);
109106 else
110107 ParseErrorMessage = "Error reading file '" + FNS + "'";
111108
3434 Module *llvm::CloneModule(const Module *M,
3535 DenseMap &ValueMap) {
3636 // First off, we need to create the new module...
37 Module *New = new Module(M->getModuleIdentifier());
37 Module *New = new Module(M->getModuleIdentifier(), M->getContext());
3838 New->setDataLayout(M->getDataLayout());
3939 New->setTargetTriple(M->getTargetTriple());
4040 New->setModuleInlineAsm(M->getModuleInlineAsm());
1717 #include "llvm/DerivedTypes.h"
1818 #include "llvm/GlobalVariable.h"
1919 #include "llvm/GlobalAlias.h"
20 #include "llvm/LLVMContext.h"
2021 #include "llvm/TypeSymbolTable.h"
2122 #include "llvm/ModuleProvider.h"
2223 #include "llvm/InlineAsm.h"
3738 }
3839
3940
41 /*===-- Operations on contexts --------------------------------------------===*/
42
43 LLVMContextRef LLVMContextCreate() {
44 return wrap(new LLVMContext());
45 }
46
47 void LLVMContextDispose(LLVMContextRef C) {
48 delete unwrap(C);
49 }
50
51
4052 /*===-- Operations on modules ---------------------------------------------===*/
4153
42 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {
43 return wrap(new Module(ModuleID));
54 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID, LLVMContextRef C) {
55 return wrap(new Module(ModuleID, unwrap(C)));
4456 }
4557
4658 void LLVMDisposeModule(LLVMModuleRef M) {
1414 #include "llvm/InstrTypes.h"
1515 #include "llvm/Constants.h"
1616 #include "llvm/DerivedTypes.h"
17 #include "llvm/LLVMContext.h"
1718 #include "llvm/ADT/STLExtras.h"
1819 #include "llvm/ADT/StringExtras.h"
1920 #include "llvm/Support/LeakDetector.h"
5354 // Primitive Module methods.
5455 //
5556
56 Module::Module(const std::string &MID)
57 : ModuleID(MID), DataLayout("") {
57 Module::Module(const std::string &MID, LLVMContext* C)
58 : Context(C), ModuleID(MID), DataLayout("") {
5859 ValSymTab = new ValueSymbolTable();
5960 TypeSymTab = new TypeSymbolTable();
6061 }
6363 }
6464
6565 BugDriver::BugDriver(const char *toolname, bool as_child, bool find_bugs,
66 unsigned timeout, unsigned memlimit)
67 : ToolName(toolname), ReferenceOutputFile(OutputFile),
66 unsigned timeout, unsigned memlimit, LLVMContext* ctxt)
67 : Context(ctxt), ToolName(toolname), ReferenceOutputFile(OutputFile),
6868 Program(0), Interpreter(0), SafeInterpreter(0), gcc(0),
69 run_as_child(as_child),
70 run_find_bugs(find_bugs), Timeout(timeout), MemoryLimit(memlimit) {}
69 run_as_child(as_child), run_find_bugs(find_bugs), Timeout(timeout),
70 MemoryLimit(memlimit) {}
7171
7272
7373 /// ParseInputFile - Given a bitcode or assembly input filename, parse and
7474 /// return it, or return null if not possible.
7575 ///
76 Module *llvm::ParseInputFile(const std::string &Filename) {
76 Module *llvm::ParseInputFile(const std::string &Filename, LLVMContext* Ctxt) {
7777 std::auto_ptr Buffer(MemoryBuffer::getFileOrSTDIN(Filename));
7878 Module *Result = 0;
7979 if (Buffer.get())
80 Result = ParseBitcodeFile(Buffer.get());
80 Result = ParseBitcodeFile(Buffer.get(), Ctxt);
8181
8282 ParseError Err;
83 if (!Result && !(Result = ParseAssemblyFile(Filename, Err))) {
83 if (!Result && !(Result = ParseAssemblyFile(Filename, Err, Ctxt))) {
8484 Err.PrintError("bugpoint", errs());
8585 Result = 0;
8686 }
9999
100100 try {
101101 // Load the first input file.
102 Program = ParseInputFile(Filenames[0]);
102 Program = ParseInputFile(Filenames[0], Context);
103103 if (Program == 0) return true;
104104
105105 if (!run_as_child)
106106 std::cout << "Read input file : '" << Filenames[0] << "'\n";
107107
108108 for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
109 std::auto_ptr M(ParseInputFile(Filenames[i]));
109 std::auto_ptr M(ParseInputFile(Filenames[i], Context));
110110 if (M.get() == 0) return true;
111111
112112 if (!run_as_child)
2929 class BasicBlock;
3030 class AbstractInterpreter;
3131 class Instruction;
32 class LLVMContext;
3233
3334 class DebugCrashes;
3435
4142 extern bool BugpointIsInterrupted;
4243
4344 class BugDriver {
45 LLVMContext* Context;
4446 const std::string ToolName; // Name of bugpoint
4547 std::string ReferenceOutputFile; // Name of `good' output file
4648 Module *Program; // The raw program, linked together
5961
6062 public:
6163 BugDriver(const char *toolname, bool as_child, bool find_bugs,
62 unsigned timeout, unsigned memlimit);
64 unsigned timeout, unsigned memlimit, LLVMContext* ctxt);
6365
6466 const std::string &getToolName() const { return ToolName; }
67
68 LLVMContext* getContext() { return Context; }
6569
6670 // Set up methods... these methods are used to copy information about the
6771 // command line arguments into instance variables of BugDriver.
289293 /// ParseInputFile - Given a bitcode or assembly input filename, parse and
290294 /// return it, or return null if not possible.
291295 ///
292 Module *ParseInputFile(const std::string &InputFilename);
296 Module *ParseInputFile(const std::string &InputFilename, LLVMContext* ctxt);
293297
294298
295299 /// getPassesString - Turn a list of passes into a string which indicates the
7272 PrefixOutput.set(PfxOutput);
7373 OrigProgram = BD.Program;
7474
75 BD.Program = ParseInputFile(PrefixOutput.toString());
75 BD.Program = ParseInputFile(PrefixOutput.toString(), BD.getContext());
7676 if (BD.Program == 0) {
7777 std::cerr << BD.getToolName() << ": Error reading bitcode file '"
7878 << PrefixOutput << "'!\n";
111111 // Ok, so now we know that the prefix passes work, try running the suffix
112112 // passes on the result of the prefix passes.
113113 //
114 Module *PrefixOutput = ParseInputFile(BitcodeResult);
114 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
115115 if (PrefixOutput == 0) {
116116 std::cerr << BD.getToolName() << ": Error reading bitcode file '"
117117 << BitcodeResult << "'!\n";
254254 // Restore the current program.
255255 swapProgramIn(OldProgram);
256256
257 Module *Ret = ParseInputFile(BitcodeResult);
257 Module *Ret = ParseInputFile(BitcodeResult, Context);
258258 if (Ret == 0) {
259259 cerr << getToolName() << ": Error reading bitcode file '"
260260 << BitcodeResult << "'!\n";
1515 #include "BugDriver.h"
1616 #include "ToolRunner.h"
1717 #include "llvm/LinkAllPasses.h"
18 #include "llvm/LLVMContext.h"
1819 #include "llvm/Support/PassNameParser.h"
1920 #include "llvm/Support/CommandLine.h"
2021 #include "llvm/Support/ManagedStatic.h"
7273 "llvm.org/cmds/bugpoint.html"
7374 " for more information.\n");
7475 sys::SetInterruptFunction(BugpointInterruptFunction);
75
76 BugDriver D(argv[0], AsChild, FindBugs, TimeoutValue, MemoryLimit);
76
77 LLVMContext Context;
78 BugDriver D(argv[0], AsChild, FindBugs, TimeoutValue, MemoryLimit, &Context);
7779 if (D.addSources(InputFilenames)) return 1;
7880 D.addPasses(PassList.begin(), PassList.end());
7981
2121 #include "llvm/Target/TargetMachine.h"
2222 #include "llvm/Target/TargetMachineRegistry.h"
2323 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/LLVMContext.h"
2425 #include "llvm/Module.h"
2526 #include "llvm/ModuleProvider.h"
2627 #include "llvm/PassManager.h"
211212 int main(int argc, char **argv) {
212213 sys::PrintStackTraceOnErrorSignal();
213214 PrettyStackTraceProgram X(argc, argv);
215 LLVMContext Context;
214216 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
215217 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
216218
224226 std::auto_ptr Buffer(
225227 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
226228 if (Buffer.get())
227 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
229 M.reset(ParseBitcodeFile(Buffer.get(), &Context, &ErrorMessage));
228230 if (M.get() == 0) {
229231 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
230232 std::cerr << "Reason: " << ErrorMessage << "\n";
1212 //
1313 //===----------------------------------------------------------------------===//
1414
15 #include "llvm/LLVMContext.h"
1516 #include "llvm/Module.h"
1617 #include "llvm/ModuleProvider.h"
1718 #include "llvm/Type.h"
9293 sys::PrintStackTraceOnErrorSignal();
9394 PrettyStackTraceProgram X(argc, argv);
9495
96 LLVMContext Context;
9597 atexit(do_shutdown); // Call llvm_shutdown() on exit.
9698 cl::ParseCommandLineOptions(argc, argv,
9799 "llvm interpreter & dynamic compiler\n");
103105 // Load the bitcode...
104106 std::string ErrorMsg;
105107 ModuleProvider *MP = NULL;
106 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
107 MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
108 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
109 MP = getBitcodeModuleProvider(Buffer, &Context, &ErrorMsg);
108110 if (!MP) delete Buffer;
109111 }
110112
1111 //
1212 //===----------------------------------------------------------------------===//
1313
14 #include "llvm/LLVMContext.h"
1415 #include "llvm/Module.h"
1516 #include "llvm/Bitcode/Archive.h"
1617 #include "llvm/Support/CommandLine.h"
689690 // Print a stack trace if we signal out.
690691 sys::PrintStackTraceOnErrorSignal();
691692 PrettyStackTraceProgram X(argc, argv);
693 LLVMContext Context;
692694 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
693695
694696 // Have the command line options parsed and handle things
716718 // Produce a warning if we should and we're creating the archive
717719 if (!Create)
718720 std::cerr << argv[0] << ": creating " << ArchivePath.toString() << "\n";
719 TheArchive = Archive::CreateEmpty(ArchivePath);
721 TheArchive = Archive::CreateEmpty(ArchivePath, &Context);
720722 TheArchive->writeToDisk();
721723 } else {
722724 std::string Error;
723 TheArchive = Archive::OpenAndLoad(ArchivePath, &Error);
725 TheArchive = Archive::OpenAndLoad(ArchivePath, &Context, &Error);
724726 if (TheArchive == 0) {
725727 std::cerr << argv[0] << ": error loading '" << ArchivePath << "': "
726728 << Error << "!\n";
1414 //
1515 //===----------------------------------------------------------------------===//
1616
17 #include "llvm/LLVMContext.h"
1718 #include "llvm/Module.h"
1819 #include "llvm/Assembly/Parser.h"
1920 #include "llvm/Analysis/Verifier.h"
5455 // Print a stack trace if we signal out.
5556 sys::PrintStackTraceOnErrorSignal();
5657 PrettyStackTraceProgram X(argc, argv);
58 LLVMContext Context;
5759 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
5860 cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
5961
6264 try {
6365 // Parse the file now...
6466 ParseError Err;
65 std::auto_ptr M(ParseAssemblyFile(InputFilename, Err));
67 std::auto_ptr M(ParseAssemblyFile(InputFilename, Err, &Context));
6668 if (M.get() == 0) {
6769 Err.PrintError(argv[0], errs());
6870 return 1;
2121 /// CLIDebugger constructor - This initializes the debugger to its default
2222 /// state, and initializes the command table.
2323 ///
24 CLIDebugger::CLIDebugger()
25 : TheProgramInfo(0), TheRuntimeInfo(0), Prompt("(llvm-db) "), ListSize(10) {
24 CLIDebugger::CLIDebugger(LLVMContext* ctxt)
25 : Context(ctxt), TheProgramInfo(0), TheRuntimeInfo(0),
26 Prompt("(llvm-db) "), ListSize(10) {
2627 // Initialize instance variables
2728 CurrentFile = 0;
2829 LineListedStart = 1;
2323 class SourceLanguage;
2424 class ProgramInfo;
2525 class RuntimeInfo;
26 class LLVMContext;
2627
2728 /// CLIDebugger - This class implements the command line interface for the
2829 /// LLVM debugger.
2930 class CLIDebugger {
31 LLVMContext* Context;
32
3033 /// Dbg - The low-level LLVM debugger object that we use to do our dirty
3134 /// work.
3235 Debugger Dbg;
7881 const SourceLanguage *CurrentLanguage;
7982
8083 public:
81 CLIDebugger();
84 CLIDebugger(LLVMContext* ctxt);
8285
8386 /// getDebugger - Return the current LLVM debugger implementation being
8487 /// used.
6363 TheProgramInfo = 0;
6464 CurrentFile = 0;
6565
66 Dbg.loadProgram(Program.toString());
66 Dbg.loadProgram(Program.toString(), Context);
6767 TheProgramInfo = new ProgramInfo(Dbg.getProgram());
6868 }
6969
243243 std::cout << "Unloaded program.\n";
244244 } else {
245245 std::cout << "Loading program... " << std::flush;
246 Dbg.loadProgram(Prog);
246 Dbg.loadProgram(Prog, Context);
247247 assert(Dbg.isProgramLoaded() &&
248248 "loadProgram succeeded, but not program loaded!");
249249 TheProgramInfo = new ProgramInfo(Dbg.getProgram());
1212 //===----------------------------------------------------------------------===//
1313
1414 #include "CLIDebugger.h"
15 #include "llvm/LLVMContext.h"
1516 #include "llvm/Support/CommandLine.h"
1617 #include "llvm/Support/ManagedStatic.h"
1718 #include "llvm/Support/PrettyStackTrace.h"
5354 sys::PrintStackTraceOnErrorSignal();
5455 PrettyStackTraceProgram X(argc, argv);
5556
57 LLVMContext Context;
5658 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
5759 std::cout << "NOTE: llvm-db is known useless right now.\n";
5860 try {
6769 InputArgs.push_back(InputFile);
6870
6971 // Create the CLI debugger...
70 CLIDebugger D;
72 CLIDebugger D(&Context);
7173
7274 // Initialize the debugger with the command line options we read...
7375 Debugger &Dbg = D.getDebugger();
1515 //
1616 //===----------------------------------------------------------------------===//
1717
18 #include "llvm/LLVMContext.h"
1819 #include "llvm/Module.h"
1920 #include "llvm/PassManager.h"
2021 #include "llvm/Bitcode/ReaderWriter.h"
4950 sys::PrintStackTraceOnErrorSignal();
5051 PrettyStackTraceProgram X(argc, argv);
5152
53 LLVMContext Context;
5254 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
5355 try {
5456 cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
6062
6163 if (MemoryBuffer *Buffer
6264 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
63 M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
65 M.reset(ParseBitcodeFile(Buffer, &Context, &ErrorMessage));
6466 delete Buffer;
6567 }
6668
1111 //
1212 //===----------------------------------------------------------------------===//
1313
14 #include "llvm/LLVMContext.h"
1415 #include "llvm/Module.h"
1516 #include "llvm/PassManager.h"
1617 #include "llvm/Bitcode/ReaderWriter.h"
5960 // Print a stack trace if we signal out.
6061 sys::PrintStackTraceOnErrorSignal();
6162 PrettyStackTraceProgram X(argc, argv);
62
63
64 LLVMContext Context;
6365 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
6466 cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
6567
7072 cerr << argv[0] << ": Error reading file '" + InputFilename + "'\n";
7173 return 1;
7274 } else {
73 M.reset(ParseBitcodeFile(Buffer));
75 M.reset(ParseBitcodeFile(Buffer, &Context));
7476 }
7577 delete Buffer;
7678
2121
2222 #include "llvm/LinkAllVMCore.h"
2323 #include "llvm/Linker.h"
24 #include "llvm/LLVMContext.h"
2425 #include "llvm/System/Program.h"
2526 #include "llvm/Module.h"
2627 #include "llvm/PassManager.h"
504505 // Print a stack trace if we signal out.
505506 sys::PrintStackTraceOnErrorSignal();
506507 PrettyStackTraceProgram X(argc, argv);
507
508
509 LLVMContext Context;
508510 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
509511 try {
510512 // Initial global variable above for convenience printing of program name.
514516 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
515517
516518 // Construct a Linker (now that Verbose is set)
517 Linker TheLinker(progname, OutputFilename, Verbose);
519 Linker TheLinker(progname, OutputFilename, &Context, Verbose);
518520
519521 // Keep track of the native link items (versus the bitcode items)
520522 Linker::ItemList NativeLinkItems;
1212 //===----------------------------------------------------------------------===//
1313
1414 #include "llvm/Linker.h"
15 #include "llvm/LLVMContext.h"
1516 #include "llvm/Module.h"
1617 #include "llvm/Analysis/Verifier.h"
1718 #include "llvm/Bitcode/ReaderWriter.h"
4647 // LoadFile - Read the specified bitcode file in and return it. This routine
4748 // searches the link path for the specified file to try to find it...
4849 //
49 static inline std::auto_ptr LoadFile(const std::string &FN) {
50 static inline std::auto_ptr LoadFile(const std::string &FN,
51 LLVMContext* Context) {
5052 sys::Path Filename;
5153 if (!Filename.set(FN)) {
5254 cerr << "Invalid file name: '" << FN << "'\n";
6163 const std::string &FNStr = Filename.toString();
6264 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(FNStr,
6365 &ErrorMessage)) {
64 Result = ParseBitcodeFile(Buffer, &ErrorMessage);
66 Result = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
6567 delete Buffer;
6668 }
6769 if (Result) return std::auto_ptr(Result); // Load successful!
8385 sys::PrintStackTraceOnErrorSignal();
8486 PrettyStackTraceProgram X(argc, argv);
8587
88 LLVMContext Context;
8689 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
8790 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
8891
8992 unsigned BaseArg = 0;
9093 std::string ErrorMessage;
9194
92 std::auto_ptr Composite(LoadFile(InputFilenames[BaseArg]));
95 std::auto_ptr Composite(LoadFile(InputFilenames[BaseArg], &Context));
9396 if (Composite.get() == 0) {
9497 cerr << argv[0] << ": error loading file '"
9598 << InputFilenames[BaseArg] << "'\n";
97100 }
98101
99102 for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
100 std::auto_ptr M(LoadFile(InputFilenames[i]));
103 std::auto_ptr M(LoadFile(InputFilenames[i], &Context));
101104 if (M.get() == 0) {
102105 cerr << argv[0] << ": error loading file '" <
103106 return 1;
1515 //
1616 //===----------------------------------------------------------------------===//
1717
18 #include "llvm/LLVMContext.h"
1819 #include "llvm/Module.h"
1920 #include "llvm/Bitcode/ReaderWriter.h"
2021 #include "llvm/Bitcode/Archive.h"
131132 }
132133
133134 static void DumpSymbolNamesFromFile(std::string &Filename) {
135 LLVMContext Context;
134136 std::string ErrorMessage;
135137 sys::Path aPath(Filename);
136138 // Note: Currently we do not support reading an archive from stdin.
139141 MemoryBuffer::getFileOrSTDIN(Filename, &ErrorMessage));
140142 Module *Result = 0;
141143 if (Buffer.get())
142 Result = ParseBitcodeFile(Buffer.get(), &ErrorMessage);
144 Result = ParseBitcodeFile(Buffer.get(), &Context, &ErrorMessage);
143145
144146 if (Result)
145147 DumpSymbolNamesFromModule(Result);
150152
151153 } else if (aPath.isArchive()) {
152154 std::string ErrMsg;
153 Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &ErrorMessage);
155 Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &Context,
156 &ErrorMessage);
154157 if (!archive)
155158 std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
156159 std::vector Modules;
1313 //===----------------------------------------------------------------------===//
1414
1515 #include "llvm/InstrTypes.h"
16 #include "llvm/LLVMContext.h"
1617 #include "llvm/Module.h"
1718 #include "llvm/Assembly/AsmAnnotationWriter.h"
1819 #include "llvm/Analysis/ProfileInfoLoader.h"
114115 // Print a stack trace if we signal out.
115116 sys::PrintStackTraceOnErrorSignal();
116117 PrettyStackTraceProgram X(argc, argv);
117
118
119 LLVMContext Context;
118120 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
119121 try {
120122 cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
124126 Module *M = 0;
125127 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
126128 &ErrorMessage)) {
127 M = ParseBitcodeFile(Buffer, &ErrorMessage);
129 M = ParseBitcodeFile(Buffer, &Context, &ErrorMessage);
128130 delete Buffer;
129131 }
130132 if (M == 0) {
1010 //
1111 //===----------------------------------------------------------------------===//
1212
13 #include "llvm/LLVMContext.h"
1314 #include "llvm/Module.h"
1415 #include "llvm/Bitcode/Archive.h"
1516 #include "llvm/Support/CommandLine.h"
4546 // Print a stack trace if we signal out.
4647 llvm::sys::PrintStackTraceOnErrorSignal();
4748 llvm::PrettyStackTraceProgram X(argc, argv);
48
49
50 LLVMContext Context;
4951 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
5052
5153 // Have the command line options parsed and handle things
7274
7375 std::string err_msg;
7476 std::auto_ptr
75 AutoArchive(Archive::OpenAndLoad(ArchivePath,&err_msg));
77 AutoArchive(Archive::OpenAndLoad(ArchivePath, &Context, &err_msg));
7678 Archive* TheArchive = AutoArchive.get();
7779 if (!TheArchive)
7880 throw err_msg;
6969
7070
7171 LTOCodeGenerator::LTOCodeGenerator()
72 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
72 : _context(new LLVMContext()),
73 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
7374 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
7475 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
7576 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
1515 #define LTO_CODE_GENERATOR_H
1616
1717 #include "llvm/Linker.h"
18 #include "llvm/LLVMContext.h"
1819 #include "llvm/ADT/StringMap.h"
1920 #include "llvm/ADT/SmallVector.h"
2021
5253
5354 typedef llvm::StringMap StringSet;
5455
56 llvm::LLVMContext* _context;
5557 llvm::Linker _linker;
5658 llvm::TargetMachine* _target;
5759 bool _emitDwarfDebugInfo;
1414 #include "LTOModule.h"
1515
1616 #include "llvm/Constants.h"
17 #include "llvm/LLVMContext.h"
1718 #include "llvm/Module.h"
1819 #include "llvm/ModuleProvider.h"
1920 #include "llvm/ADT/OwningPtr.h"
6667 // takes ownership of buffer
6768 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
6869 {
69 OwningPtr mp(getBitcodeModuleProvider(buffer));
70 OwningPtr mp(getBitcodeModuleProvider(buffer,
71 new LLVMContext()));
7072 // on success, mp owns buffer and both are deleted at end of this method
7173 if ( !mp ) {
7274 delete buffer;
8385 {
8486 }
8587
86 LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
88 LTOModule* LTOModule::makeLTOModule(const char* path, LLVMContext* Context,
89 std::string& errMsg)
8790 {
8891 OwningPtr buffer(MemoryBuffer::getFile(path, &errMsg));
8992 if ( !buffer )
9093 return NULL;
91 return makeLTOModule(buffer.get(), errMsg);
94 return makeLTOModule(buffer.get(), Context, errMsg);
9295 }
9396
9497 /// makeBuffer - create a MemoryBuffer from a memory range.
108111
109112
110113 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length,
114 LLVMContext* Context,
111115 std::string& errMsg)
112116 {
113117 OwningPtr buffer(makeBuffer(mem, length));
114118 if ( !buffer )
115119 return NULL;
116 return makeLTOModule(buffer.get(), errMsg);
120 return makeLTOModule(buffer.get(), Context, errMsg);
117121 }
118122
119123 /// getFeatureString - Return a string listing the features associated with the
135139 return Features.getString();
136140 }
137141
138 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
142 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, LLVMContext* Context,
143 std::string& errMsg)
139144 {
140145 // parse bitcode buffer
141 OwningPtr m(ParseBitcodeFile(buffer, &errMsg));
146 OwningPtr m(ParseBitcodeFile(buffer, Context, &errMsg));
142147 if ( !m )
143148 return NULL;
144149 // find machine architecture for this module
3131 class GlobalValue;
3232 class Value;
3333 class Function;
34 class LLVMContext;
3435 }
3536
3637
4950 static bool isBitcodeFileForTarget(const char* path,
5051 const char* triplePrefix);
5152
52 static LTOModule* makeLTOModule(const char* path, std::string& errMsg);
53 static LTOModule* makeLTOModule(const char* path,
54 llvm::LLVMContext* Context,
55 std::string& errMsg);
5356 static LTOModule* makeLTOModule(const void* mem, size_t length,
54 std::string& errMsg);
57 llvm::LLVMContext* Context,
58 std::string& errMsg);
5559
5660 const char* getTargetTriple();
5761 uint32_t getSymbolCount();
8286 bool objcClassNameFromExpression(llvm::Constant* c,
8387 std::string& name);
8488
85 static bool isTargetMatch(llvm::MemoryBuffer* memBuffer,
89 static bool isTargetMatch(llvm::MemoryBuffer* memBuffer,
8690 const char* triplePrefix);
8791
88 static LTOModule* makeLTOModule(llvm::MemoryBuffer* buffer,
92 static LTOModule* makeLTOModule(llvm::MemoryBuffer* buffer,
93 llvm::LLVMContext* Context,
8994 std::string& errMsg);
9095 static llvm::MemoryBuffer* makeBuffer(const void* mem, size_t length);
9196
1212 //===----------------------------------------------------------------------===//
1313
1414 #include "llvm-c/lto.h"
15 #include "llvm-c/Core.h"
1516
1617 #include "LTOModule.h"
1718 #include "LTOCodeGenerator.h"
8485 // loads an object file from disk
8586 // returns NULL on error (check lto_get_error_message() for details)
8687 //
87 lto_module_t lto_module_create(const char* path)
88 {
89 return LTOModule::makeLTOModule(path, sLastErrorString);
88 lto_module_t lto_module_create(const char* path, LLVMContextRef Ctxt)
89 {
90 return LTOModule::makeLTOModule(path, llvm::unwrap(Ctxt),
91 sLastErrorString);
9092 }
9193
9294
9496 // loads an object file from memory
9597 // returns NULL on error (check lto_get_error_message() for details)
9698 //
97 lto_module_t lto_module_create_from_memory(const void* mem, size_t length)
98 {
99 return LTOModule::makeLTOModule(mem, length, sLastErrorString);
99 lto_module_t lto_module_create_from_memory(const void* mem, size_t length,
100 LLVMContextRef Ctxt)
101 {
102 return LTOModule::makeLTOModule(mem, length, llvm::unwrap(Ctxt),
103 sLastErrorString);
100104 }
101105
102106
1111 //
1212 //===----------------------------------------------------------------------===//
1313
14 #include "llvm/LLVMContext.h"
1415 #include "llvm/Module.h"
1516 #include "llvm/ModuleProvider.h"
1617 #include "llvm/PassManager.h"
309310 //
310311 int main(int argc, char **argv) {
311312 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
313 LLVMContext Context;
312314 try {
313315 cl::ParseCommandLineOptions(argc, argv,
314316 "llvm .bc -> .bc modular optimizer and analysis printer\n");
324326 std::auto_ptr M;
325327 if (MemoryBuffer *Buffer
326328 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
327 M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
329 M.reset(ParseBitcodeFile(Buffer, &Context, &ErrorMessage));
328330 delete Buffer;
329331 }
330332