1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
|
//===- GenerateCode.cpp - Functions for generating executable files ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains functions for generating executable files once linking
// has finished. This includes generating a shell script to run the JIT or
// a native executable derived from the bytecode.
//
//===----------------------------------------------------------------------===//
#include "gccld.h"
#include "llvm/System/Program.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/Archive.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
namespace {
cl::opt<bool>
DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
cl::opt<bool>
Verify("verify", cl::desc("Verify intermediate results of all passes"));
cl::opt<bool>
DisableOptimizations("disable-opt",
cl::desc("Do not run any optimization passes"));
}
/// CopyEnv - This function takes an array of environment variables and makes a
/// copy of it. This copy can then be manipulated any way the caller likes
/// without affecting the process's real environment.
///
/// Inputs:
/// envp - An array of C strings containing an environment.
///
/// Return value:
/// NULL - An error occurred.
///
/// Otherwise, a pointer to a new array of C strings is returned. Every string
/// in the array is a duplicate of the one in the original array (i.e. we do
/// not copy the char *'s from one array to another).
///
static char ** CopyEnv(char ** const envp) {
// Count the number of entries in the old list;
unsigned entries; // The number of entries in the old environment list
for (entries = 0; envp[entries] != NULL; entries++)
/*empty*/;
// Add one more entry for the NULL pointer that ends the list.
++entries;
// If there are no entries at all, just return NULL.
if (entries == 0)
return NULL;
// Allocate a new environment list.
char **newenv = new char* [entries];
if ((newenv = new char* [entries]) == NULL)
return NULL;
// Make a copy of the list. Don't forget the NULL that ends the list.
entries = 0;
while (envp[entries] != NULL) {
newenv[entries] = new char[strlen (envp[entries]) + 1];
strcpy (newenv[entries], envp[entries]);
++entries;
}
newenv[entries] = NULL;
return newenv;
}
/// RemoveEnv - Remove the specified environment variable from the environment
/// array.
///
/// Inputs:
/// name - The name of the variable to remove. It cannot be NULL.
/// envp - The array of environment variables. It cannot be NULL.
///
/// Notes:
/// This is mainly done because functions to remove items from the environment
/// are not available across all platforms. In particular, Solaris does not
/// seem to have an unsetenv() function or a setenv() function (or they are
/// undocumented if they do exist).
///
static void RemoveEnv(const char * name, char ** const envp) {
for (unsigned index=0; envp[index] != NULL; index++) {
// Find the first equals sign in the array and make it an EOS character.
char *p = strchr (envp[index], '=');
if (p == NULL)
continue;
else
*p = '\0';
// Compare the two strings. If they are equal, zap this string.
// Otherwise, restore it.
if (!strcmp(name, envp[index]))
*envp[index] = '\0';
else
*p = '=';
}
}
static void dumpArgs(const char **args) {
std::cerr << *args++;
while (*args)
std::cerr << ' ' << *args++;
std::cerr << '\n' << std::flush;
}
static inline void addPass(PassManager &PM, Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
}
static bool isBytecodeLibrary(const sys::Path &FullPath) {
// Check for a bytecode file
if (FullPath.isBytecodeFile()) return true;
// Check for a dynamic library file
if (FullPath.isDynamicLibrary()) return false;
// Check for a true bytecode archive file
if (FullPath.isArchive() ) {
std::string ErrorMessage;
Archive* ar = Archive::OpenAndLoadSymbols( FullPath, &ErrorMessage );
return ar->isBytecodeArchive();
}
return false;
}
static bool isBytecodeLPath(const std::string &LibPath) {
sys::Path LPath(LibPath);
// Make sure it exists and is a directory
sys::FileStatus Status;
if (LPath.getFileStatus(Status) || !Status.isDir)
return false;
// Grab the contents of the -L path
std::set<sys::Path> Files;
if (LPath.getDirectoryContents(Files, 0))
return false;
// Iterate over the contents one by one to determine
// if this -L path has any bytecode shared libraries
// or archives
std::set<sys::Path>::iterator File = Files.begin();
std::string dllsuffix = sys::Path::GetDLLSuffix();
for (; File != Files.end(); ++File) {
// Not a file?
if (File->getFileStatus(Status) || Status.isDir)
continue;
std::string path = File->toString();
// Check for an ending '.dll', '.so' or '.a' suffix as all
// other files are not of interest to us here
if (path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
&& path.find(".a", path.size()-2) == std::string::npos)
continue;
// Finally, check to see if the file is a true bytecode file
if (isBytecodeLibrary(*File))
return true;
}
return false;
}
/// GenerateBytecode - generates a bytecode file from the specified module.
///
/// Inputs:
/// M - The module for which bytecode should be generated.
/// StripLevel - 2 if we should strip all symbols, 1 if we should strip
/// debug info.
/// Internalize - Flags whether all symbols should be marked internal.
/// Out - Pointer to file stream to which to write the output.
///
/// Returns non-zero value on error.
///
int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
std::ostream *Out) {
// In addition to just linking the input from GCC, we also want to spiff it up
// a little bit. Do this now.
PassManager Passes;
if (Verify) Passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
addPass(Passes, new TargetData(M));
// Often if the programmer does not specify proper prototypes for the
// functions they are calling, they end up calling a vararg version of the
// function that does not get a body filled in (the real function has typed
// arguments). This pass merges the two functions.
addPass(Passes, createFunctionResolvingPass());
if (!DisableOptimizations) {
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
addPass(Passes, createInternalizePass(Internalize));
// Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function
// pointers passed as arguments to direct uses of functions.
addPass(Passes, createIPSCCPPass());
// Now that we internalized some globals, see if we can hack on them!
addPass(Passes, createGlobalOptimizerPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant...
addPass(Passes, createConstantMergePass());
// Remove unused arguments from functions...
addPass(Passes, createDeadArgEliminationPass());
if (!DisableInline)
addPass(Passes, createFunctionInliningPass()); // Inline small functions
addPass(Passes, createPruneEHPass()); // Remove dead EH info
addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again.
addPass(Passes, createGlobalDCEPass()); // Remove dead functions
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
addPass(Passes, createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
addPass(Passes, createInstructionCombiningPass());
addPass(Passes, createPredicateSimplifierPass());
addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
// Run a few AA driven optimizations here and now, to cleanup the code.
addPass(Passes, createGlobalsModRefPass()); // IP alias analysis
addPass(Passes, createLICMPass()); // Hoist loop invariants
addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
addPass(Passes, createGCSEPass()); // Remove common subexprs
addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
// Cleanup and simplify the code after the scalar optimizations.
addPass(Passes, createInstructionCombiningPass());
// Delete basic blocks, which optimization passes may have killed...
addPass(Passes, createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions...
addPass(Pa
|