1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
3 // This utility is intended to be compatible with GCC, and follows standard
4 // system 'ld' conventions. As such, the default output file is ./a.out.
5 // Additionally, this program outputs a shell script that is used to invoke LLI
6 // to execute the program. In this manner, the generated executable (a.out for
7 // example), is directly executable, whereas the bytecode file actually lives in
8 // the a.out.bc file generated by this program. Also, Force is on by default.
10 // Note that if someone (or a script) deletes the executable program generated,
11 // the .bc file will be left around. Considering that this is a temporary hack,
12 // I'm not too worried about this.
14 //===----------------------------------------------------------------------===//
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/WriteBytecodePass.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Transforms/Utils/Linker.h"
25 #include "Support/CommandLine.h"
26 #include "Support/FileUtilities.h"
27 #include "Support/Signals.h"
28 #include "Support/SystemUtils.h"
34 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
38 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
39 cl::value_desc("filename"));
42 Verbose("v", cl::desc("Print information about actions taken"));
45 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
46 cl::value_desc("directory"));
49 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
50 cl::value_desc("library prefix"));
53 Strip("s", cl::desc("Strip symbol info from executable"));
56 NoInternalize("disable-internalize",
57 cl::desc("Do not mark all symbols as internal"));
59 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
60 cl::aliasopt(NoInternalize));
63 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
64 " library, not an executable"));
68 cl::desc("Generate a native binary instead of a shell script"));
70 // Compatibility options that are ignored but supported by LD
72 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
74 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
76 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
78 CO6("r", cl::Hidden, cl::desc("Compatibility option: ignored"));
82 // Function: PrintAndReturn ()
85 // Prints a message (usually error message) to standard error (stderr) and
86 // returns a value usable for an exit status.
89 // progname - The name of the program (i.e. argv[0]).
90 // Message - The message to print to standard error.
91 // Extra - Extra information to print between the program name and thei
92 // message. It is optional.
98 // Returns a value that can be used as the exit status (i.e. for exit()).
101 PrintAndReturn (const char *progname,
102 const std::string &Message,
103 const std::string &Extra)
105 std::cerr << progname << Extra << ": " << Message << "\n";
111 // Function: CopyEnv()
114 // This function takes an array of environment variables and makes a
115 // copy of it. This copy can then be manipulated any way the caller likes
116 // without affecting the process's real environment.
119 // envp - An array of C strings containing an environment.
125 // NULL - An error occurred.
127 // Otherwise, a pointer to a new array of C strings is returned. Every string
128 // in the array is a duplicate of the one in the original array (i.e. we do
129 // not copy the char *'s from one array to another).
131 char ** CopyEnv(char ** const envp) {
132 // Count the number of entries in the old list;
133 unsigned entries; // The number of entries in the old environment list
134 for (entries = 0; envp[entries] != NULL; entries++)
139 // Add one more entry for the NULL pointer that ends the list.
142 // If there are no entries at all, just return NULL.
146 // Allocate a new environment list.
148 if ((newenv = new (char *) [entries]) == NULL)
151 // Make a copy of the list. Don't forget the NULL that ends the list.
153 while (envp[entries] != NULL) {
154 newenv[entries] = new char[strlen (envp[entries]) + 1];
155 strcpy (newenv[entries], envp[entries]);
158 newenv[entries] = NULL;
165 // Function: RemoveEnv()
168 // Remove the specified environment variable from the environment array.
171 // name - The name of the variable to remove. It cannot be NULL.
172 // envp - The array of environment variables. It cannot be NULL.
175 // envp - The pointer to the specified variable name is removed.
181 // This is mainly done because functions to remove items from the environment
182 // are not available across all platforms. In particular, Solaris does not
183 // seem to have an unsetenv() function or a setenv() function (or they are
184 // undocumented if they do exist).
186 void RemoveEnv(const char * name, char ** const envp) {
187 for (unsigned index=0; envp[index] != NULL; index++) {
188 // Find the first equals sign in the array and make it an EOS character.
189 char *p = strchr (envp[index], '=');
195 // Compare the two strings. If they are equal, zap this string.
196 // Otherwise, restore it.
197 if (!strcmp(name, envp[index]))
207 int main(int argc, char **argv, char **envp) {
208 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
210 std::string ErrorMessage;
211 std::auto_ptr<Module> Composite(LoadObject(InputFilenames[0], ErrorMessage));
212 if (Composite.get() == 0)
213 return PrintAndReturn(argv[0], ErrorMessage);
215 // We always look first in the current directory when searching for libraries.
216 LibPaths.insert(LibPaths.begin(), ".");
218 // If the user specified an extra search path in their environment, respect
220 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
221 LibPaths.push_back(SearchPath);
223 // Remove any consecutive duplicates of the same library...
224 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
227 // Link in all of the files
228 if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
229 return 1; // Error already printed
230 LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths, Verbose, Native);
232 // Link in all of the libraries next...
234 // Create the output file.
235 std::string RealBytecodeOutput = OutputFilename;
236 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
237 std::ofstream Out(RealBytecodeOutput.c_str());
239 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
242 // Ensure that the bytecode file gets removed from the disk if we get a
244 RemoveFileOnSignal(RealBytecodeOutput);
246 // Generate the bytecode file.
247 if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
249 return PrintAndReturn(argv[0], "error generating bytcode");
252 // Close the bytecode file.
255 // If we are not linking a library, generate either a native executable
256 // or a JIT shell script, depending upon what the user wants.
257 if (!LinkAsLibrary) {
258 // If the user wants to generate a native executable, compile it from the
261 // Otherwise, create a script that will run the bytecode through the JIT.
263 // Name of the Assembly Language output file
264 std::string AssemblyFile = OutputFilename + ".s";
266 // Mark the output files for removal if we get an interrupt.
267 RemoveFileOnSignal(AssemblyFile);
268 RemoveFileOnSignal(OutputFilename);
270 // Determine the locations of the llc and gcc programs.
271 std::string llc = FindExecutable("llc", argv[0]);
272 std::string gcc = FindExecutable("gcc", argv[0]);
274 return PrintAndReturn(argv[0], "Failed to find llc");
277 return PrintAndReturn(argv[0], "Failed to find gcc");
279 // Generate an assembly language file for the bytecode.
280 if (Verbose) std::cout << "Generating Assembly Code\n";
281 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
282 if (Verbose) std::cout << "Generating Native Code\n";
283 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
286 // Remove the assembly language file.
287 removeFile (AssemblyFile);
289 // Output the script to start the program...
290 std::ofstream Out2(OutputFilename.c_str());
292 return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
294 Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
298 // Make the script executable...
299 MakeFileExecutable(OutputFilename);
301 // Make the bytecode file readable and directly executable in LLEE as well
302 MakeFileExecutable(RealBytecodeOutput);
303 MakeFileReadable(RealBytecodeOutput);