llvm.org GIT mirror llvm / 7533809
Remove llvm-ld and llvm-stub (which is only used by llvm-ld). llvm-ld is no longer useful and causes confusion and so it is being removed. * Does not work very well on Windows because it must call a gcc like driver to assemble and link. * Has lots of hard coded paths which are wrong on many systems. * Does not understand most of ld's options. * Can be partially replaced by llvm-link | opt | {llc | as, llc -filetype=obj} | ld, or fully replaced by Clang. I know of no production use of llvm-ld, and hacking use should be replaced by Clang's driver. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@155147 91177308-0d34-0410-b5e6-96231b3b80d8 Michael J. Spencer 7 years ago
30 changed file(s) with 34 addition(s) and 1515 deletion(s). Raw diff Collapse all Expand all
535535 LLVM_CONFIG := $(BuildLLVMToolDir)/llvm-config$(BUILD_EXEEXT)
536536 else
537537 LLVM_CONFIG := $(LLVMToolDir)/llvm-config$(EXEEXT)
538 endif
539 ifndef LLVMLD
540 LLVMLD := $(LLVMToolDir)/llvm-ld$(EXEEXT)
541538 endif
542539 ifndef LLVMDIS
543540 LLVMDIS := $(LLVMToolDir)/llvm-dis$(EXEEXT)
4343 causes the crash, and reduce the file down to a small example which triggers the
4444 crash.

4545
46

For detailed case scenarios, such as debugging opt,

47 llvm-ld, or one of the LLVM code generators, see
48 href="HowToSubmitABug.html">How To Submit a Bug Report document.

46

For detailed case scenarios, such as debugging opt, or one of the

47 LLVM code generators, see How To Submit a Bug
48 Report document.

4949
5050
5151
6161
6262
  • llvm-prof -
  • 6363 format raw `llvmprof.out' data into a human-readable report
    64
    65
  • llvm-ld -
  • 66 general purpose linker with loadable runtime optimization support
    6764
    6865
  • llvm-config -
  • 6966 print out LLVM compilation options, libraries, etc. as configured
    +0
    -234
    docs/CommandGuide/llvm-ld.pod less more
    None =pod
    1
    2 =head1 NAME
    3
    4 llvm-ld - LLVM linker
    5
    6 =head1 SYNOPSIS
    7
    8 B
    9
    10 =head1 DESCRIPTION
    11
    12 The B tool takes a set of LLVM bitcode files and links them
    13 together into a single LLVM bitcode file. The output bitcode file can be
    14 another bitcode file or an executable bitcode program. Using additional
    15 options, B is able to produce native code executables.
    16
    17 The B tool is the main linker for LLVM. It is used to link together
    18 the output of LLVM front-end compilers and run "link time" optimizations (mostly
    19 the inter-procedural kind).
    20
    21 The B tools attempts to mimic the interface provided by the default
    22 system linker so that it can act as a I replacement.
    23
    24 =head2 Search Order
    25
    26 When looking for objects specified on the command line, B will search
    27 for the object first in the current directory and then in the directory
    28 specified by the B environment variable. If it cannot
    29 find the object, it fails.
    30
    31 When looking for a library specified with the B<-l> option, B first
    32 attempts to load a file with that name from the current directory. If that
    33 fails, it looks for libI.bc, libI.a, or libI.I
    34 library extension>, in that order, in each directory added to the library search
    35 path with the B<-L> option. These directories are searched in the order they
    36 are specified. If the library cannot be located, then B looks in the
    37 directory specified by the B environment variable. If it
    38 does not find a library there, it fails.
    39
    40 The I may be I<.so>, I<.dyld>, I<.dll>, or something
    41 different, depending upon the system.
    42
    43 The B<-L> option is global. It does not matter where it is specified in the
    44 list of command line arguments; the directory is simply added to the search path
    45 and is applied to all libraries, preceding or succeeding, in the command line.
    46
    47 =head2 Link order
    48
    49 All object and bitcode files are linked first in the order they were
    50 specified on the command line. All library files are linked next.
    51 Some libraries may not be linked into the object program; see below.
    52
    53 =head2 Library Linkage
    54
    55 Object files and static bitcode objects are always linked into the output
    56 file. Library archives (.a files) load only the objects within the archive
    57 that define symbols needed by the output file. Hence, libraries should be
    58 listed after the object files and libraries which need them; otherwise, the
    59 library may not be linked in, and the dependent library will not have its
    60 undefined symbols defined.
    61
    62 =head2 Native code generation
    63
    64 The B program has limited support for native code generation, when
    65 using the B<-native> or B<-native-cbe> options. Native code generation is
    66 performed by converting the linked bitcode into native assembly (.s) or C code
    67 and running the system compiler (typically gcc) on the result.
    68
    69 =head1 OPTIONS
    70
    71 =head2 General Options
    72
    73 =over
    74
    75 =item B<-help>
    76
    77 Print a summary of command line options.
    78
    79 =item B<-v>
    80
    81 Specifies verbose mode. In this mode the linker will print additional
    82 information about the actions it takes, programs it executes, etc.
    83
    84 =item B<-stats>
    85
    86 Print statistics.
    87
    88 =item B<-time-passes>
    89
    90 Record the amount of time needed for each pass and print it to standard
    91 error.
    92
    93 =back
    94
    95 =head2 Input/Output Options
    96
    97 =over
    98
    99 =item B<-o> F
    100
    101 This overrides the default output file and specifies the name of the file that
    102 should be generated by the linker. By default, B generates a file named
    103 F for compatibility with B. The output will be written to
    104 F.
    105
    106 =item B<-b> F
    107
    108 This option can be used to override the output bitcode file name. By default,
    109 the name of the bitcode output file is one more ".bc" suffix added to the name
    110 specified by B<-o filename> option.
    111
    112 =item B<-l>F
    113
    114 This option specifies the F of a library to search when resolving symbols
    115 for the program. Only the base name should be specified as F, without a
    116 F prefix or any suffix.
    117
    118 =item B<-L>F
    119
    120 This option tells B to look in F to find any library subsequently
    121 specified with the B<-l> option. The paths will be searched in the order in
    122 which they are specified on the command line. If the library is still not found,
    123 a small set of system specific directories will also be searched. Note that
    124 libraries specified with the B<-l> option that occur I any B<-L> options
    125 will not search the paths given by the B<-L> options following it.
    126
    127 =item B<-link-as-library>
    128
    129 Link the bitcode files together as a library, not an executable. In this mode,
    130 undefined symbols will be permitted.
    131
    132 =item B<-r>
    133
    134 An alias for -link-as-library.
    135
    136 =item B<-native>
    137
    138 Generate a native machine code executable.
    139
    140 When generating native executables, B first checks for a bitcode
    141 version of the library and links it in, if necessary. If the library is
    142 missing, B skips it. Then, B links in the same
    143 libraries as native code.
    144
    145 In this way, B should be able to link in optimized bitcode
    146 subsets of common libraries and then link in any part of the library that
    147 hasn't been converted to bitcode.
    148
    149 =item B<-native-cbe>
    150
    151 Generate a native machine code executable with the LLVM C backend.
    152
    153 This option is identical to the B<-native> option, but uses the
    154 C backend to generate code for the program instead of an LLVM native
    155 code generator.
    156
    157 =back
    158
    159 =head2 Optimization Options
    160
    161 =over
    162
    163 =item B<-disable-inlining>
    164
    165 Do not run the inlining pass. Functions will not be inlined into other
    166 functions.
    167
    168 =item B<-disable-opt>
    169
    170 Completely disable optimization.
    171
    172 =item B<-disable-internalize>
    173
    174 Do not mark all symbols as internal.
    175
    176 =item B<-verify-each>
    177
    178 Run the verification pass after each of the passes to verify intermediate
    179 results.
    180
    181 =item B<-strip-all>
    182
    183 Strip all debug and symbol information from the executable to make it smaller.
    184
    185 =item B<-strip-debug>
    186
    187 Strip all debug information from the executable to make it smaller.
    188
    189 =item B<-s>
    190
    191 An alias for B<-strip-all>.
    192
    193 =item B<-S>
    194
    195 An alias for B<-strip-debug>.
    196
    197 =item B<-export-dynamic>
    198
    199 An alias for B<-disable-internalize>
    200
    201 =item B<-post-link-opt>F
    202
    203 Run post-link optimization program. After linking is completed a bitcode file
    204 will be generated. It will be passed to the program specified by F as the
    205 first argument. The second argument to the program will be the name of a
    206 temporary file into which the program should place its optimized output. For
    207 example, the "no-op optimization" would be a simple shell script:
    208
    209 #!/bin/bash
    210 cp $1 $2
    211
    212 =back
    213
    214 =head1 EXIT STATUS
    215
    216 If B succeeds, it will exit with 0 return code. If an error occurs,
    217 it will exit with a non-zero return code.
    218
    219 =head1 ENVIRONMENT
    220
    221 The C environment variable is used to find bitcode
    222 libraries. Any paths specified in this variable will be searched after the C<-L>
    223 options.
    224
    225 =head1 SEE ALSO
    226
    227 L
    228
    229 =head1 AUTHORS
    230
    231 Maintained by the LLVM Team (L).
    232
    233 =cut
    1818
    1919
  • License
  • 2020
    21
  • Why are the LLVM source code and the front-end distributed under
  • 22 different licenses?
    23
    2421
  • Does the University of Illinois Open Source License really qualify as an
  • 2522 "open source" license?
    2623
    7168
  • After Subversion update, rebuilding gives the error "No rule to make
  • 7269 target".
    7370
    74
  • When I compile LLVM-GCC with srcdir == objdir,
  • 75 it fails. Why?
    7671
    7772
    7873
  • Source Languages
  • 9085 instruction. Help!
    9186
    9287
    93
  • Using the GCC Front End
  • 88
  • Using the C and C++ Front Ends
  • 9489
    95
  • When I compile software that uses a configure script, the configure
  • 96 script thinks my system has all of the header files and libraries it is
    97 testing for. How do I get configure to work correctly?
    98
    99
  • When I compile code using the LLVM GCC front end, it complains that it
  • 100 cannot find libcrtend.a?
    101
    102
  • How can I disable all optimizations when compiling code using the LLVM
  • 103 GCC front end?
    104
    105
  • Can I use LLVM to convert C++ code to C
  • 106 code?
    107
    10890
  • Can I compile C or C++ code to
  • 10991 platform-independent LLVM bitcode?
    11092
    11193
    11294
    113
  • Questions about code generated by the GCC front-end
  • 95
  • Questions about code generated by the demo page
  • 11496
    11597
  • What is this llvm.global_ctors and
  • 116 _GLOBAL__I__tmp_webcompile... stuff that happens when I
    98 _GLOBAL__I_a... stuff that happens when I
    11799 #include <iostream>?
    118100
    119101
  • Where did all of my code go??
  • 142124
    143125
    144126
    145

    Why are the LLVM source code and the front-end distributed under different

    146 licenses?

    147
    148
    149
    150

    The C/C++ front-ends are based on GCC and must be distributed under the GPL.

    151 Our aim is to distribute LLVM source code under a much less
    152 restrictive license, in particular one that does not compel users who
    153 distribute tools based on modifying the source to redistribute the modified
    154 source code as well.

    155
    156
    157
    158127

    Does the University of Illinois Open Source License really qualify as an

    159128 "open source" license?

    160129
    218187

    Some porting problems may exist in the following areas:

    219188
    220189
    221
  • The GCC front end code is not as portable as the LLVM suite, so it may not
  • 222 compile as well on unsupported platforms.
    223
    224
  • The LLVM build system relies heavily on UNIX shell tools, like the Bourne
  • 225 Shell and sed. Porting to systems without these tools (MacOS 9, Plan 9)
    226 will require more effort.
    190
  • The autoconf/makefile build system relies heavily on UNIX shell tools,
  • 191 like the Bourne Shell and sed. Porting to systems without these tools
    192 (MacOS 9, Plan 9) Will require more effort.
    227193
    228194
    229195
    255221
    256222
    257223

    The configure script finds the right C compiler, but it uses the

    258 LLVM linker from a previous build. What do I do?

    224 LLVM tools from a previous build. What do I do?

    259225
    260226
    261227
    425391 rebuilding.

    426392
    427393
    428
    429

    When I compile LLVM-GCC with srcdir == objdir, it

    430 fails. Why?

    431
    432
    433
    434

    The GNUmakefile in the top-level directory of LLVM-GCC is a special

    435 Makefile used by Apple to invoke the build_gcc script after
    436 setting up a special environment. This has the unfortunate side-effect that
    437 trying to build LLVM-GCC with srcdir == objdir in a "non-Apple way" invokes
    438 the GNUmakefile instead of Makefile. Because the
    439 environment isn't set up correctly to do this, the build fails.

    440
    441

    People not building LLVM-GCC the "Apple way" need to build LLVM-GCC with

    442 srcdir != objdir, or simply remove the GNUmakefile entirely.

    443
    444

    We regret the inconvenience.

    445
    446
    447394
    448395
    449396
    459406
    460407
    461408

    LLVM currently has full support for C and C++ source languages. These are

    462 available through a special version of GCC that LLVM calls the
    463 C Front End

    464
    465

    There is an incomplete version of a Java front end available in the

    466 java module. There is no documentation on this yet so you'll need to
    467 download the code, compile it, and try it.

    409 available through both Clang and
    410 DragonEgg.

    468411
    469412

    The PyPy developers are working on integrating LLVM into the PyPy backend so

    470413 that PyPy language can translate to LLVM.

    557500
    558501
    559502

    560 Using the GCC Front End
    503 Using the C and C++ Front Ends
    561504
    562505
    563506
    564
    565
    566

    When I compile software that uses a configure script, the configure script

    567 thinks my system has all of the header files and libraries it is testing for.
    568 How do I get configure to work correctly?

    569
    570
    571
    572

    The configure script is getting things wrong because the LLVM linker allows

    573 symbols to be undefined at link time (so that they can be resolved during JIT
    574 or translation to the C back end). That is why configure thinks your system
    575 "has everything."

    576
    577

    To work around this, perform the following steps:

    578
    579
    580
  • Make sure the CC and CXX environment variables contains the full path to
  • 581 the LLVM GCC front end.
    582
    583
  • Make sure that the regular C compiler is first in your PATH.
  • 584
    585
  • Add the string "-Wl,-native" to your CFLAGS environment variable.
  • 586
    587
    588

    This will allow the llvm-ld linker to create a native code

    589 executable instead of shell script that runs the JIT. Creating native code
    590 requires standard linkage, which in turn will allow the configure script to
    591 find out if code is not linking on your system because the feature isn't
    592 available on your system.

    593
    594
    595
    596

    When I compile code using the LLVM GCC front end, it complains that it cannot

    597 find libcrtend.a.
    598

    599
    600
    601
    602

    The only way this can happen is if you haven't installed the runtime

    603 library. To correct this, do:

    604
    605
    
                      
                    
    606 % cd llvm/runtime
    607 % make clean ; make install-bytecode
    608
    609
    610
    611
    612

    How can I disable all optimizations when compiling code using the LLVM GCC

    613 front end?

    614
    615
    616
    617

    Passing "-Wa,-disable-opt -Wl,-disable-opt" will disable *all* cleanup and

    618 optimizations done at the llvm level, leaving you with the truly horrible
    619 code that you desire.

    620
    621
    622
    623
    624

    Can I use LLVM to convert C++ code to C code?

    625
    626
    627
    628

    Yes, you can use LLVM to convert code from any language LLVM supports to C.

    629 Note that the generated C code will be very low level (all loops are lowered
    630 to gotos, etc) and not very pretty (comments are stripped, original source
    631 formatting is totally lost, variables are renamed, expressions are
    632 regrouped), so this may not be what you're looking for. Also, there are
    633 several limitations noted below.

    634
    635

    Use commands like this:

    636
    637
    638
  • Compile your program with llvm-g++:

  • 639
    640
    
                      
                    
    641 % llvm-g++ -emit-llvm x.cpp -o program.bc -c
    642
    643
    644

    or:

    645
    646
    
                      
                    
    647 % llvm-g++ a.cpp -c -emit-llvm
    648 % llvm-g++ b.cpp -c -emit-llvm
    649 % llvm-ld a.o b.o -o program
    650
    651
    652

    This will generate program and program.bc. The .bc

    653 file is the LLVM version of the program all linked together.

    654
    655
  • Convert the LLVM code to C code, using the LLC tool with the C

  • 656 backend:

    657
    658
    
                      
                    
    659 % llc -march=c program.bc -o program.c
    660
    661
    662
  • Finally, compile the C file:

  • 663
    664
    
                      
                    
    665 % cc x.c -lstdc++
    666
    667
    668
    669
    670

    Using LLVM does not eliminate the need for C++ library support. If you use

    671 the llvm-g++ front-end, the generated code will depend on g++'s C++ support
    672 libraries in the same way that code generated from g++ would. If you use
    673 another C++ front-end, the generated code will depend on whatever library
    674 that front-end would normally require.

    675
    676

    If you are working on a platform that does not provide any C++ libraries, you

    677 may be able to manually compile libstdc++ to LLVM bitcode, statically link it
    678 into your program, then use the commands above to convert the whole result
    679 into C code. Alternatively, you might compile the libraries and your
    680 application into two different chunks of C code and link them.

    681
    682

    Note that, by default, the C back end does not support exception handling.

    683 If you want/need it for a certain program, you can enable it by passing
    684 "-enable-correct-eh-support" to the llc program. The resultant code will use
    685 setjmp/longjmp to implement exception support that is relatively slow, and
    686 not C++-ABI-conforming on most platforms, but otherwise correct.

    687
    688

    Also, there are a number of other limitations of the C backend that cause it

    689 to produce code that does not fully conform to the C++ ABI on most
    690 platforms. Some of the C++ programs in LLVM's test suite are known to fail
    691 when compiled with the C back end because of ABI incompatibilities with
    692 standard C++ libraries.

    693
    694507
    695508
    696509

    Can I compile C or C++ code to

    718531
    719532
    720533

    721 Questions about code generated by the GCC front-end
    534 Questions about code generated by the demo page
    722535
    723536
    724537
    725538
    726539
    727540

    What is this llvm.global_ctors and

    728 _GLOBAL__I__tmp_webcompile... stuff that happens when I #include
    541 _GLOBAL__I_a... stuff that happens when I #include
    729542 <iostream>?

    730543
    731544
    15091509
    The disassembler transforms the LLVM bitcode to human readable
    15101510 LLVM assembly.
    15111511
    1512
    llvm-ld
    1513
    llvm-ld is a general purpose and extensible linker for LLVM.
    1514 It performs standard link time optimizations and allows optimization
    1515 modules to be loaded and run so that language specific optimizations can
    1516 be applied at link time.
    1517
    15181512
    llvm-link
    15191513
    llvm-link, not surprisingly, links multiple LLVM modules into
    15201514 a single program.
    603603
    604604
  • llvm-stress is a command line tool for generating random .ll files to fuzz
  • 605605 different LLVM components.
    606
  • llvm-ld has been removed. Use llvm-link or Clang instead.
  • 606607
  • ....
  • 607608
    608609
    252252

    LLVM provides a wide variety of optimizations that can be used in certain

    253253 circumstances. Some documentation about the various
    254254 passes is available, but it isn't very complete. Another good source of
    255 ideas can come from looking at the passes that llvm-gcc or
    256 llvm-ld run to get started. The "opt" tool allows you to
    257 experiment with passes from the command line, so you can see if they do
    258 anything.

    255 ideas can come from looking at the passes that Clang runs to get
    256 started. The "opt" tool allows you to experiment with passes from the
    257 command line, so you can see if they do anything.

    259258
    260259

    Now that we have reasonable code coming out of our front-end, lets talk about

    261260 executing it!

    269269

    LLVM provides a wide variety of optimizations that can be used in certain

    270270 circumstances. Some documentation about the various
    271271 passes is available, but it isn't very complete. Another good source of
    272 ideas can come from looking at the passes that llvm-gcc or
    273 llvm-ld run to get started. The "opt" tool allows you to
    274 experiment with passes from the command line, so you can see if they do
    275 anything.

    272 ideas can come from looking at the passes that Clang runs to get
    273 started. The "opt" tool allows you to experiment with passes from the
    274 command line, so you can see if they do anything.

    276275
    277276

    Now that we have reasonable code coming out of our front-end, lets talk about

    278277 executing it!

    2020 // ./BrainF prog.bf #Write as BitCode
    2121 //
    2222 // lli prog.bf.bc #Run generated BitCode
    23 // llvm-ld -native -o=prog prog.bf.bc #Compile BitCode into native executable
    2423 //
    2524 //===--------------------------------------------------------------------===//
    2625
    462462 endif
    463463 endif
    464464 LLVM_CONFIG := $(LLVMToolDir)/llvm-config
    465 ifndef LLVMLD
    466 LLVMLD := $(LLVMToolDir)/llvm-ld$(EXEEXT)
    467 endif
    468465 ifndef LLVMDIS
    469466 LLVMDIS := $(LLVMToolDir)/llvm-dis$(EXEEXT)
    470467 endif
    7474 UnitTests
    7575 BugpointPasses LLVMHello
    7676 llc lli llvm-ar llvm-as llvm-dis llvm-extract llvm-dwarfdump
    77 llvm-ld llvm-link llvm-mc llvm-nm llvm-objdump llvm-readobj
    77 llvm-link llvm-mc llvm-nm llvm-objdump llvm-readobj
    7878 macho-dump opt
    7979 FileCheck count not json-bench)
    8080 set_target_properties(check.deps PROPERTIES FOLDER "Tests")
    0 ; RUN: llvm-as < %s > %t.bc
    11 ; RUN: llvm-as < %p/2008-03-07-DroppedSection_b.ll > %t2.bc
    2 ; RUN: llvm-ld -r -disable-opt %t.bc %t2.bc -o %t3.bc
    2 ; RUN: llvm-link %t.bc %t2.bc -o %t3.bc
    33 ; RUN: llvm-dis < %t3.bc | grep ".data.init_task"
    44
    55 ; ModuleID = 't.bc'
    0 ; RUN: llvm-as < %s > %t.bc
    11 ; RUN: llvm-as < %p/2008-03-07-DroppedSection_a.ll > %t2.bc
    2 ; RUN: llvm-ld -r -disable-opt %t.bc %t2.bc -o %t3.bc
    2 ; RUN: llvm-link %t.bc %t2.bc -o %t3.bc
    33 ; RUN: llvm-dis < %t3.bc | grep ".data.init_task"
    44
    55 ; ModuleID = 'u.bc'
    +0
    -16
    test/Linker/link-archive.ll less more
    None ; Test linking of a bc file to an archive via llvm-ld.
    1 ; PR1434
    2 ; RUN: rm -f %t.bar.a %t.foo.a
    3 ; RUN: llvm-as %s -o %t.bar.bc
    4 ; RUN: echo {define i32* @foo(i32 %x) \{ ret i32* @baz \} \
    5 ; RUN: @baz = external global i32 } | llvm-as -o %t.foo.bc
    6 ; RUN: llvm-ar rcf %t.foo.a %t.foo.bc
    7 ; RUN: llvm-ar rcf %t.bar.a %t.bar.bc
    8 ; RUN: llvm-ld -disable-opt %t.bar.bc %t.foo.a -o %t.bc
    9 ; RUN: llvm-ld -disable-opt %t.foo.bc %t.bar.a -o %t.bc
    10 declare i32* @foo(...)
    11 define i32* @bar() {
    12 %ret = call i32* (...)* @foo( i32 123 )
    13 ret i32* %ret
    14 }
    15 @baz = global i32 0
    11 ; that error is printed out.
    22 ; RUN: llvm-as %s -o %t.one.bc
    33 ; RUN: llvm-as %s -o %t.two.bc
    4 ; RUN: not llvm-ld -disable-opt -link-as-library %t.one.bc %t.two.bc \
    5 ; RUN: -o %t.bc 2>%t.err
    6 ; RUN: grep "symbol multiply defined" %t.err
    4 ; RUN: not llvm-link %t.one.bc %t.two.bc -o %t.bc |& FileCheck %s
    75
    6 ; CHECK: symbol multiply defined
    87 define i32 @bar() {
    9 ret i32 0
    8 ret i32 0
    109 }
    186186 r"\bllvm-bcanalyzer\b", r"\bllvm-config\b",
    187187 r"\bllvm-cov\b", r"\bllvm-diff\b",
    188188 r"\bllvm-dis\b", r"\bllvm-dwarfdump\b",
    189 r"\bllvm-extract\b", r"\bllvm-ld\b",
    189 r"\bllvm-extract\b",
    190190 r"\bllvm-link\b", r"\bllvm-mc\b",
    191191 r"\bllvm-nm\b", r"\bllvm-objdump\b",
    192192 r"\bllvm-prof\b", r"\bllvm-ranlib\b",
    193193 r"\bllvm-rtdyld\b", r"\bllvm-shlib\b",
    194 r"\bllvm-size\b", r"\bllvm-stub\b",
    194 r"\bllvm-size\b",
    195195 # Don't match '-llvmc'.
    196196 r"(?
    197197 # Don't match '.opt', '-opt',
    2626 add_subdirectory(llvm-nm)
    2727 add_subdirectory(llvm-size)
    2828
    29 add_subdirectory(llvm-ld)
    3029 add_subdirectory(llvm-cov)
    3130 add_subdirectory(llvm-prof)
    3231 add_subdirectory(llvm-link)
    4342 add_subdirectory(bugpoint)
    4443 add_subdirectory(bugpoint-passes)
    4544 add_subdirectory(llvm-bcanalyzer)
    46 add_subdirectory(llvm-stub)
    4745 add_subdirectory(llvm-stress)
    4846
    4947 if( NOT WIN32 )
    1515 ;===------------------------------------------------------------------------===;
    1616
    1717 [common]
    18 subdirectories = bugpoint llc lli llvm-ar llvm-as llvm-bcanalyzer llvm-cov llvm-diff llvm-dis llvm-dwarfdump llvm-extract llvm-ld llvm-link llvm-mc llvm-nm llvm-objdump llvm-prof llvm-ranlib llvm-rtdyld llvm-size llvm-stub macho-dump opt
    18 subdirectories = bugpoint llc lli llvm-ar llvm-as llvm-bcanalyzer llvm-cov llvm-diff llvm-dis llvm-dwarfdump llvm-extract llvm-link llvm-mc llvm-nm llvm-objdump llvm-prof llvm-ranlib llvm-rtdyld llvm-size macho-dump opt
    1919
    2020 [component_0]
    2121 type = Group
    2828 DIRS := llvm-config
    2929 PARALLEL_DIRS := opt llvm-as llvm-dis \
    3030 llc llvm-ranlib llvm-ar llvm-nm \
    31 llvm-ld llvm-prof llvm-link \
    31 llvm-prof llvm-link \
    3232 lli llvm-extract llvm-mc \
    33 bugpoint llvm-bcanalyzer llvm-stub \
    33 bugpoint llvm-bcanalyzer \
    3434 llvm-diff macho-dump llvm-objdump llvm-readobj \
    3535 llvm-rtdyld llvm-dwarfdump llvm-cov \
    3636 llvm-size llvm-stress
    +0
    -8
    tools/llvm-ld/CMakeLists.txt less more
    None set(LLVM_LINK_COMPONENTS ipo scalaropts linker archive bitwriter vectorize)
    1
    2 add_llvm_tool(llvm-ld
    3 Optimize.cpp
    4 llvm-ld.cpp
    5 )
    6
    7 add_dependencies(llvm-ld llvm-stub)
    +0
    -22
    tools/llvm-ld/LLVMBuild.txt less more
    None ;===- ./tools/llvm-ld/LLVMBuild.txt ----------------------------*- Conf -*--===;
    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 is an LLVMBuild description file for the components in this subdirectory.
    10 ;
    11 ; For more information on the LLVMBuild system, please see:
    12 ;
    13 ; http://llvm.org/docs/LLVMBuild.html
    14 ;
    15 ;===------------------------------------------------------------------------===;
    16
    17 [component_0]
    18 type = Tool
    19 name = llvm-ld
    20 parent = Tools
    21 required_libraries = Archive BitWriter IPO Linker Scalar
    +0
    -14
    tools/llvm-ld/Makefile less more
    None ##===- tools/llvm-ld/Makefile ------------------------------*- Makefile -*-===##
    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 LEVEL := ../..
    10 TOOLNAME := llvm-ld
    11 LINK_COMPONENTS := ipo scalaropts linker archive bitwriter vectorize
    12
    13 include $(LEVEL)/Makefile.common
    +0
    -130
    tools/llvm-ld/Optimize.cpp less more
    None //===- Optimize.cpp - Optimize a complete program -------------------------===//
    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 implements all optimization of the linked module for llvm-ld.
    10 //
    11 //===----------------------------------------------------------------------===//
    12
    13 #include "llvm/Module.h"
    14 #include "llvm/PassManager.h"
    15 #include "llvm/Analysis/Verifier.h"
    16 #include "llvm/Support/CommandLine.h"
    17 #include "llvm/Support/raw_ostream.h"
    18 #include "llvm/Support/DynamicLibrary.h"
    19 #include "llvm/Target/TargetData.h"
    20 #include "llvm/Target/TargetMachine.h"
    21 #include "llvm/Support/PassNameParser.h"
    22 #include "llvm/Support/PluginLoader.h"
    23 #include "llvm/Transforms/IPO.h"
    24 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
    25 #include "llvm/Transforms/Scalar.h"
    26 using namespace llvm;
    27
    28 // Pass Name Options as generated by the PassNameParser
    29 static cl::list
    30 OptimizationList(cl::desc("Optimizations available:"));
    31
    32 //Don't verify at the end
    33 static cl::opt DontVerify("disable-verify", cl::ReallyHidden);
    34
    35 static cl::opt DisableInline("disable-inlining",
    36 cl::desc("Do not run the inliner pass"));
    37
    38 static cl::opt
    39 DisableOptimizations("disable-opt",
    40 cl::desc("Do not run any optimization passes"));
    41
    42 static cl::opt DisableInternalize("disable-internalize",
    43 cl::desc("Do not mark all symbols as internal"));
    44
    45 static cl::opt VerifyEach("verify-each",
    46 cl::desc("Verify intermediate results of all passes"));
    47
    48 static cl::alias ExportDynamic("export-dynamic",
    49 cl::aliasopt(DisableInternalize),
    50 cl::desc("Alias for -disable-internalize"));
    51
    52 static cl::opt Strip("strip-all",
    53 cl::desc("Strip all symbol info from executable"));
    54
    55 static cl::alias A0("s", cl::desc("Alias for --strip-all"),
    56 cl::aliasopt(Strip));
    57
    58 static cl::opt StripDebug("strip-debug",
    59 cl::desc("Strip debugger symbol info from executable"));
    60
    61 static cl::alias A1("S", cl::desc("Alias for --strip-debug"),
    62 cl::aliasopt(StripDebug));
    63
    64 // A utility function that adds a pass to the pass manager but will also add
    65 // a verifier pass after if we're supposed to verify.
    66 static inline void addPass(PassManager &PM, Pass *P) {
    67 // Add the pass to the pass manager...
    68 PM.add(P);
    69
    70 // If we are verifying all of the intermediate steps, add the verifier...
    71 if (VerifyEach)
    72 PM.add(createVerifierPass());
    73 }
    74
    75 namespace llvm {
    76 /// Optimize - Perform link time optimizations. This will run the scalar
    77 /// optimizations, any loaded plugin-optimization modules, and then the
    78 /// inter-procedural optimizations if applicable.
    79 void Optimize(Module *M) {
    80
    81 // Instantiate the pass manager to organize the passes.
    82 PassManager Passes;
    83
    84 // If we're verifying, start off with a verification pass.
    85 if (VerifyEach)
    86 Passes.add(createVerifierPass());
    87
    88 // Add an appropriate TargetData instance for this module...
    89 addPass(Passes, new TargetData(M));
    90
    91 if (!DisableOptimizations)
    92 PassManagerBuilder().populateLTOPassManager(Passes, !DisableInternalize,
    93 !DisableInline);
    94
    95 // If the -s or -S command line options were specified, strip the symbols out
    96 // of the resulting program to make it smaller. -s and -S are GNU ld options
    97 // that we are supporting; they alias -strip-all and -strip-debug.
    98 if (Strip || StripDebug)
    99 addPass(Passes, createStripSymbolsPass(StripDebug && !Strip));
    100
    101 // Create a new optimization pass for each one specified on the command line
    102 std::auto_ptr target;
    103 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
    104 const PassInfo *Opt = OptimizationList[i];
    105 if (Opt->getNormalCtor())
    106 addPass(Passes, Opt->getNormalCtor()());
    107 else
    108 errs() << "llvm-ld: cannot create pass: " << Opt->getPassName()
    109 << "\n";
    110 }
    111
    112 // The user's passes may leave cruft around. Clean up after them them but
    113 // only if we haven't got DisableOptimizations set
    114 if (!DisableOptimizations) {
    115 addPass(Passes, createInstructionCombiningPass());
    116 addPass(Passes, createCFGSimplificationPass());
    117 addPass(Passes, createAggressiveDCEPass());
    118 addPass(Passes, createGlobalDCEPass());
    119 }
    120
    121 // Make sure everything is still good.
    122 if (!DontVerify)
    123 Passes.add(createVerifierPass());
    124
    125 // Run our queue of passes all at once now, efficiently.
    126 Passes.run(*M);
    127 }
    128
    129 }
    +0
    -732
    tools/llvm-ld/llvm-ld.cpp less more
    None //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
    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 utility is intended to be compatible with GCC, and follows standard
    10 // system 'ld' conventions. As such, the default output file is ./a.out.
    11 // Additionally, this program outputs a shell script that is used to invoke LLI
    12 // to execute the program. In this manner, the generated executable (a.out for
    13 // example), is directly executable, whereas the bitcode file actually lives in
    14 // the a.out.bc file generated by this program.
    15 //
    16 // Note that if someone (or a script) deletes the executable program generated,
    17 // the .bc file will be left around. Considering that this is a temporary hack,
    18 // I'm not too worried about this.
    19 //
    20 //===----------------------------------------------------------------------===//
    21
    22 #include "llvm/LinkAllVMCore.h"
    23 #include "llvm/Linker.h"
    24 #include "llvm/LLVMContext.h"
    25 #include "llvm/Support/Program.h"
    26 #include "llvm/Module.h"
    27 #include "llvm/PassManager.h"
    28 #include "llvm/Bitcode/ReaderWriter.h"
    29 #include "llvm/Target/TargetData.h"
    30 #include "llvm/Target/TargetMachine.h"
    31 #include "llvm/Support/CommandLine.h"
    32 #include "llvm/Support/FileUtilities.h"
    33 #include "llvm/Support/ManagedStatic.h"
    34 #include "llvm/Support/MemoryBuffer.h"
    35 #include "llvm/Support/PrettyStackTrace.h"
    36 #include "llvm/Support/SystemUtils.h"
    37 #include "llvm/Support/ToolOutputFile.h"
    38 #include "llvm/Support/Signals.h"
    39 #include
    40 #include
    41 using namespace llvm;
    42
    43 // Rightly this should go in a header file but it just seems such a waste.
    44 namespace llvm {
    45 extern void Optimize(Module*);
    46 }
    47
    48 // Input/Output Options
    49 static cl::list InputFilenames(cl::Positional, cl::OneOrMore,
    50 cl::desc(""));
    51
    52 static cl::opt OutputFilename("o", cl::init("a.out"),
    53 cl::desc("Override output filename"),
    54 cl::value_desc("filename"));
    55
    56 static cl::opt BitcodeOutputFilename("b", cl::init(""),
    57 cl::desc("Override bitcode output filename"),
    58 cl::value_desc("filename"));
    59
    60 static cl::opt Verbose("v",
    61 cl::desc("Print information about actions taken"));
    62
    63 static cl::list LibPaths("L", cl::Prefix,
    64 cl::desc("Specify a library search path"),
    65 cl::value_desc("directory"));
    66
    67 static cl::list FrameworkPaths("F", cl::Prefix,
    68 cl::desc("Specify a framework search path"),
    69 cl::value_desc("directory"));
    70
    71 static cl::list Libraries("l", cl::Prefix,
    72 cl::desc("Specify libraries to link to"),
    73 cl::value_desc("library prefix"));
    74
    75 static cl::list Frameworks("framework",
    76 cl::desc("Specify frameworks to link to"),
    77 cl::value_desc("framework"));
    78
    79 // Options to control the linking, optimization, and code gen processes
    80 static cl::opt LinkAsLibrary("link-as-library",
    81 cl::desc("Link the .bc files together as a library, not an executable"));
    82
    83 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
    84 cl::desc("Alias for -link-as-library"));
    85
    86 static cl::opt Native("native",
    87 cl::desc("Generate a native binary instead of a shell script"));
    88
    89 static cl::optNativeCBE("native-cbe",
    90 cl::desc("Generate a native binary with the C backend and GCC"));
    91
    92 static cl::list PostLinkOpts("post-link-opts",
    93 cl::value_desc("path"),
    94 cl::desc("Run one or more optimization programs after linking"));
    95
    96 static cl::list XLinker("Xlinker", cl::value_desc("option"),
    97 cl::desc("Pass options to the system linker"));
    98
    99 // Compatibility options that llvm-ld ignores but are supported for
    100 // compatibility with LD
    101 static cl::opt CO3("soname", cl::Hidden,
    102 cl::desc("Compatibility option: ignored"));
    103
    104 static cl::opt CO4("version-script", cl::Hidden,
    105 cl::desc("Compatibility option: ignored"));
    106
    107 static cl::opt CO5("eh-frame-hdr", cl::Hidden,
    108 cl::desc("Compatibility option: ignored"));
    109
    110 static cl::opt CO6("h", cl::Hidden,
    111 cl::desc("Compatibility option: ignored"));
    112
    113 static cl::opt CO7("start-group", cl::Hidden,
    114 cl::desc("Compatibility option: ignored"));
    115
    116 static cl::opt CO8("end-group", cl::Hidden,
    117 cl::desc("Compatibility option: ignored"));
    118
    119 static cl::opt CO9("m", cl::Hidden,
    120 cl::desc("Compatibility option: ignored"));
    121
    122 /// This is just for convenience so it doesn't have to be passed around
    123 /// everywhere.
    124 static std::string progname;
    125
    126 /// FileRemover objects to clean up output files in the event of an error.
    127 static FileRemover OutputRemover;
    128 static FileRemover BitcodeOutputRemover;
    129
    130 /// PrintAndExit - Prints a message to standard error and exits with error code
    131 ///
    132 /// Inputs:
    133 /// Message - The message to print to standard error.
    134 ///
    135 static void PrintAndExit(const std::string &Message, Module *M, int errcode = 1) {
    136 errs() << progname << ": " << Message << "\n";
    137 delete M;
    138 llvm_shutdown();
    139 exit(errcode);
    140 }
    141
    142 static void PrintCommand(const std::vector &args) {
    143 std::vector::const_iterator I = args.begin(), E = args.end();
    144 for (; I != E; ++I)
    145 if (*I)
    146 errs() << "'" << *I << "'" << " ";
    147 errs() << "\n";
    148 }
    149
    150 /// CopyEnv - This function takes an array of environment variables and makes a
    151 /// copy of it. This copy can then be manipulated any way the caller likes
    152 /// without affecting the process's real environment.
    153 ///
    154 /// Inputs:
    155 /// envp - An array of C strings containing an environment.
    156 ///
    157 /// Return value:
    158 /// NULL - An error occurred.
    159 ///
    160 /// Otherwise, a pointer to a new array of C strings is returned. Every string
    161 /// in the array is a duplicate of the one in the original array (i.e. we do
    162 /// not copy the char *'s from one array to another).
    163 ///
    164 static char ** CopyEnv(char ** const envp) {
    165 // Count the number of entries in the old list;
    166 unsigned entries; // The number of entries in the old environment list
    167 for (entries = 0; envp[entries] != NULL; entries++)
    168 /*empty*/;
    169
    170 // Add one more entry for the NULL pointer that ends the list.
    171 ++entries;
    172
    173 // If there are no entries at all, just return NULL.
    174 if (entries == 0)
    175 return NULL;
    176
    177 // Allocate a new environment list.
    178 char **newenv = new char* [entries];
    179 if (newenv == NULL)
    180 return NULL;
    181
    182 // Make a copy of the list. Don't forget the NULL that ends the list.
    183 entries = 0;
    184 while (envp[entries] != NULL) {
    185 size_t len = strlen(envp[entries]) + 1;
    186 newenv[entries] = new char[len];
    187 memcpy(newenv[entries], envp[entries], len);
    188 ++entries;
    189 }
    190 newenv[entries] = NULL;
    191
    192 return newenv;
    193 }
    194
    195
    196 /// RemoveEnv - Remove the specified environment variable from the environment
    197 /// array.
    198 ///
    199 /// Inputs:
    200 /// name - The name of the variable to remove. It cannot be NULL.
    201 /// envp - The array of environment variables. It cannot be NULL.
    202 ///
    203 /// Notes:
    204 /// This is mainly done because functions to remove items from the environment
    205 /// are not available across all platforms. In particular, Solaris does not
    206 /// seem to have an unsetenv() function or a setenv() function (or they are
    207 /// undocumented if they do exist).
    208 ///
    209 static void RemoveEnv(const char * name, char ** const envp) {
    210 for (unsigned index=0; envp[index] != NULL; index++) {
    211 // Find the first equals sign in the array and make it an EOS character.
    212 char *p = strchr (envp[index], '=');
    213 if (p == NULL)
    214 continue;
    215 else
    216 *p = '\0';
    217
    218 // Compare the two strings. If they are equal, zap this string.
    219 // Otherwise, restore it.
    220 if (!strcmp(name, envp[index]))
    221 *envp[index] = '\0';
    222 else
    223 *p = '=';
    224 }
    225
    226 return;
    227 }
    228
    229 /// GenerateBitcode - generates a bitcode file from the module provided
    230 void GenerateBitcode(Module* M, const std::string& FileName) {
    231
    232 if (Verbose)
    233 errs() << "Generating Bitcode To " << FileName << '\n';
    234
    235 // Create the output file.
    236 std::string ErrorInfo;
    237 tool_output_file Out(FileName.c_str(), ErrorInfo,
    238 raw_fd_ostream::F_Binary);
    239 if (!ErrorInfo.empty()) {
    240 PrintAndExit(ErrorInfo, M);
    241 return;
    242 }
    243
    244 // Write it out
    245 WriteBitcodeToFile(M, Out.os());
    246 Out.keep();
    247 }
    248
    249 /// GenerateAssembly - generates a native assembly language source file from the
    250 /// specified bitcode file.
    251 ///
    252 /// Inputs:
    253 /// InputFilename - The name of the input bitcode file.
    254 /// OutputFilename - The name of the file to generate.
    255 /// llc - The pathname to use for LLC.
    256 /// envp - The environment to use when running LLC.
    257 ///
    258 /// Return non-zero value on error.
    259 ///
    260 static int GenerateAssembly(const std::string &OutputFilename,
    261 const std::string &InputFilename,
    262 const sys::Path &llc,
    263 std::string &ErrMsg ) {
    264 // Run LLC to convert the bitcode file into assembly code.
    265 std::vector args;
    266 args.push_back(llc.c_str());
    267 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
    268 // regardless of what the target in the bitcode file is.
    269 args.push_back("-x86-asm-syntax=att");
    270 args.push_back("-o");
    271 args.push_back(OutputFilename.c_str());
    272 args.push_back(InputFilename.c_str());
    273 args.push_back(0);
    274
    275 if (Verbose) {
    276 errs() << "Generating Assembly With: \n";
    277 PrintCommand(args);
    278 }
    279
    280 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
    281 }
    282
    283 /// GenerateCFile - generates a C source file from the specified bitcode file.
    284 static int GenerateCFile(const std::string &OutputFile,
    285 const std::string &InputFile,
    286 const sys::Path &llc,
    287 std::string& ErrMsg) {
    288 // Run LLC to convert the bitcode file into C.
    289 std::vector args;
    290 args.push_back(llc.c_str());
    291 args.push_back("-march=c");
    292 args.push_back("-o");
    293 args.push_back(OutputFile.c_str());
    294 args.push_back(InputFile.c_str());
    295 args.push_back(0);
    296
    297 if (Verbose) {
    298 errs() << "Generating C Source With: \n";
    299 PrintCommand(args);
    300 }
    301
    302 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
    303 }
    304
    305 /// GenerateNative - generates a native object file from the
    306 /// specified bitcode file.
    307 ///
    308 /// Inputs:
    309 /// InputFilename - The name of the input bitcode file.
    310 /// OutputFilename - The name of the file to generate.
    311 /// NativeLinkItems - The native libraries, files, code with which to link
    312 /// LibPaths - The list of directories in which to find libraries.
    313 /// FrameworksPaths - The list of directories in which to find frameworks.
    314 /// Frameworks - The list of frameworks (dynamic libraries)
    315 /// gcc - The pathname to use for GGC.
    316 /// envp - A copy of the process's current environment.
    317 ///
    318 /// Outputs:
    319 /// None.
    320 ///
    321 /// Returns non-zero value on error.
    322 ///
    323 static int GenerateNative(const std::string &OutputFilename,
    324 const std::string &InputFilename,
    325 const Linker::ItemList &LinkItems,
    326 const sys::Path &gcc, char ** const envp,
    327 std::string& ErrMsg) {
    328 // Remove these environment variables from the environment of the
    329 // programs that we will execute. It appears that GCC sets these
    330 // environment variables so that the programs it uses can configure
    331 // themselves identically.
    332 //
    333 // However, when we invoke GCC below, we want it to use its normal
    334 // configuration. Hence, we must sanitize its environment.
    335 char ** clean_env = CopyEnv(envp);
    336 if (clean_env == NULL)
    337 return 1;
    338 RemoveEnv("LIBRARY_PATH", clean_env);
    339 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
    340 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
    341 RemoveEnv("COMPILER_PATH", clean_env);
    342 RemoveEnv("COLLECT_GCC", clean_env);
    343
    344
    345 // Run GCC to assemble and link the program into native code.
    346 //
    347 // Note:
    348 // We can't just assemble and link the file with the system assembler
    349 // and linker because we don't know where to put the _start symbol.
    350 // GCC mysteriously knows how to do it.
    351 std::vector args;
    352 args.push_back(gcc.c_str());
    353 args.push_back("-fno-strict-aliasing");
    354 args.push_back("-O3");
    355 args.push_back("-o");
    356 args.push_back(OutputFilename);
    357 args.push_back(InputFilename);
    358
    359 // Add in the library and framework paths
    360 for (unsigned index = 0; index < LibPaths.size(); index++) {
    361 args.push_back("-L" + LibPaths[index]);
    362 }
    363 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
    364 args.push_back("-F" + FrameworkPaths[index]);
    365 }
    366
    367 // Add the requested options
    368 for (unsigned index = 0; index < XLinker.size(); index++)
    369 args.push_back(XLinker[index]);
    370
    371 // Add in the libraries to link.
    372 for (unsigned index = 0; index < LinkItems.size(); index++)
    373 if (LinkItems[index].first != "crtend") {
    374 if (LinkItems[index].second)
    375 args.push_back("-l" + LinkItems[index].first);
    376 else
    377 args.push_back(LinkItems[index].first);
    378 }
    379
    380 // Add in frameworks to link.
    381 for (unsigned index = 0; index < Frameworks.size(); index++) {
    382 args.push_back("-framework");
    383 args.push_back(Frameworks[index]);
    384 }
    385
    386 // Now that "args" owns all the std::strings for the arguments, call the c_str
    387 // method to get the underlying string array. We do this game so that the
    388 // std::string array is guaranteed to outlive the const char* array.
    389 std::vector Args;
    390 for (unsigned i = 0, e = args.size(); i != e; ++i)
    391 Args.push_back(args[i].c_str());
    392 Args.push_back(0);
    393
    394 if (Verbose) {
    395 errs() << "Generating Native Executable With:\n";
    396 PrintCommand(Args);
    397 }
    398
    399 // Run the compiler to assembly and link together the program.
    400 int R = sys::Program::ExecuteAndWait(
    401 gcc, &Args[0], const_cast(clean_env), 0, 0, 0, &ErrMsg);
    402 delete [] clean_env;
    403 return R;
    404 }
    405
    406 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
    407 /// bitcode file for the program.
    408 static void EmitShellScript(char **argv, Module *M) {
    409 if (Verbose)
    410 errs() << "Emitting Shell Script\n";
    411 #if defined(_WIN32)
    412 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
    413 // support windows systems, we copy the llvm-stub.exe executable from the
    414 // build tree to the destination file.
    415 std::string ErrMsg;
    416 sys::Path llvmstub = PrependMainExecutablePath("llvm-stub", argv[0],
    417 (void *)(intptr_t)&Optimize);
    418 if (llvmstub.isEmpty())
    419 PrintAndExit("Could not find llvm-stub.exe executable!", M);
    420
    421 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
    422 PrintAndExit(ErrMsg, M);
    423
    424 return;
    425 #else
    426
    427 // Output the script to start the program...
    428 std::string ErrorInfo;
    429 tool_output_file Out2(OutputFilename.c_str(), ErrorInfo);
    430 if (!ErrorInfo.empty())
    431 PrintAndExit(ErrorInfo, M);
    432
    433 Out2.os() << "#!/bin/sh\n";
    434 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
    435 Out2.os() << "lli=${LLVMINTERP-lli}\n";
    436 Out2.os() << "exec $lli \\\n";
    437 // gcc accepts -l and implicitly searches /lib and /usr/lib.
    438 LibPaths.push_back("/lib");
    439 LibPaths.push_back("/usr/lib");
    440 LibPaths.push_back("/usr/X11R6/lib");
    441 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
    442 // shared object at all! See RH 8: plain text.
    443 std::vector::iterator libc =
    444 std::find(Libraries.begin(), Libraries.end(), "c");
    445 if (libc != Libraries.end()) Libraries.erase(libc);
    446 // List all the shared object (native) libraries this executable will need
    447 // on the command line, so that we don't have to do this manually!
    448 for (std::vector::iterator i = Libraries.begin(),
    449 e = Libraries.end(); i != e; ++i) {
    450 // try explicit -L arguments first:
    451 sys::Path FullLibraryPath;
    452 for (cl::list::const_iterator P = LibPaths.begin(),
    453 E = LibPaths.end(); P != E; ++P) {
    454 FullLibraryPath = *P;
    455 FullLibraryPath.appendComponent("lib" + *i);
    456 FullLibraryPath.appendSuffix(sys::Path::GetDLLSuffix());
    457 if (!FullLibraryPath.isEmpty()) {
    458 if (!FullLibraryPath.isDynamicLibrary()) {
    459 // Not a native shared library; mark as invalid
    460 FullLibraryPath = sys::Path();
    461 } else break;
    462 }
    463 }
    464 if (FullLibraryPath.isEmpty())
    465 FullLibraryPath = sys::Path::FindLibrary(*i);
    466 if (!FullLibraryPath.isEmpty())
    467 Out2.os() << " -load=" << FullLibraryPath.str() << " \\\n";
    468 }
    469 Out2.os() << " " << BitcodeOutputFilename << " ${1+\"$@\"}\n";
    470 Out2.keep();
    471 #endif
    472 }
    473
    474 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
    475 // linker function by combining the Files and Libraries in the order they were
    476 // declared on the command line.
    477 static void BuildLinkItems(
    478 Linker::ItemList& Items,
    479 const cl::list& Files,
    480 const cl::list& Libraries) {
    481
    482 // Build the list of linkage items for LinkItems.
    483
    484 cl::list::const_iterator fileIt = Files.begin();
    485 cl::list::const_iterator libIt = Libraries.begin();
    486
    487 int libPos = -1, filePos = -1;
    488 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
    489 if (libIt != Libraries.end())
    490 libPos = Libraries.getPosition(libIt - Libraries.begin());
    491 else
    492 libPos = -1;
    493 if (fileIt != Files.end())
    494 filePos = Files.getPosition(fileIt - Files.begin());
    495 else
    496 filePos = -1;
    497
    498 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
    499 // Add a source file
    500 Items.push_back(std::make_pair(*fileIt++, false));
    501 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
    502 // Add a library
    503 Items.push_back(std::make_pair(*libIt++, true));
    504 }
    505 }
    506 }
    507
    508 int main(int argc, char **argv, char **envp) {
    509 // Print a stack trace if we signal out.
    510 sys::PrintStackTraceOnErrorSignal();
    511 PrettyStackTraceProgram X(argc, argv);
    512
    513 LLVMContext &Context = getGlobalContext();
    514 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
    515
    516 // Initialize passes
    517 PassRegistry &Registry = *PassRegistry::getPassRegistry();
    518 initializeCore(Registry);
    519 initializeScalarOpts(Registry);
    520 initializeIPO(Registry);
    521 initializeAnalysis(Registry);
    522 initializeIPA(Registry);
    523 initializeTransformUtils(Registry);
    524 initializeInstCombine(Registry);
    525 initializeTarget(Registry);
    526
    527 // Initial global variable above for convenience printing of program name.
    528 progname = sys::path::stem(argv[0]);
    529
    530 // Parse the command line options
    531 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
    532
    533 #if defined(_WIN32) || defined(__CYGWIN__)
    534 if (!LinkAsLibrary) {
    535 // Default to "a.exe" instead of "a.out".
    536 if (OutputFilename.getNumOccurrences() == 0)
    537 OutputFilename = "a.exe";
    538
    539 // If there is no suffix add an "exe" one.
    540 if (sys::path::extension(OutputFilename).empty())
    541 OutputFilename.append(".exe");
    542 }
    543 #endif
    544
    545 // Generate the bitcode for the optimized module.
    546 // If -b wasn't specified, use the name specified
    547 // with -o to construct BitcodeOutputFilename.
    548 if (BitcodeOutputFilename.empty()) {
    549 BitcodeOutputFilename = OutputFilename;
    550 if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
    551 }
    552
    553 // Arrange for the bitcode output file to be deleted on any errors.
    554 BitcodeOutputRemover.setFile(BitcodeOutputFilename);
    555 sys::RemoveFileOnSignal(sys::Path(BitcodeOutputFilename));
    556
    557 // Arrange for the output file to be deleted on any errors.
    558 if (!LinkAsLibrary) {
    559 OutputRemover.setFile(OutputFilename);
    560 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
    561 }
    562
    563 // Construct a Linker (now that Verbose is set)
    564 Linker TheLinker(progname, OutputFilename, Context, Verbose);
    565
    566 // Keep track of the native link items (versus the bitcode items)
    567 Linker::ItemList NativeLinkItems;
    568
    569 // Add library paths to the linker
    570 TheLinker.addPaths(LibPaths);
    571 TheLinker.addSystemPaths();
    572
    573 // Remove any consecutive duplicates of the same library...
    574 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
    575 Libraries.end());
    576
    577 if (LinkAsLibrary) {
    578 std::vector Files;
    579 for (unsigned i = 0; i < InputFilenames.size(); ++i )
    580 Files.push_back(sys::Path(InputFilenames[i]));
    581 if (TheLinker.LinkInFiles(Files))
    582 return 1; // Error already printed
    583
    584 // The libraries aren't linked in but are noted as "dependent" in the
    585 // module.
    586 for (cl::list::const_iterator I = Libraries.begin(),
    587 E = Libraries.end(); I != E ; ++I) {
    588 TheLinker.getModule()->addLibrary(*I);
    589 }
    590 } else {
    591 // Build a list of the items from our command line
    592 Linker::ItemList Items;
    593 BuildLinkItems(Items, InputFilenames, Libraries);
    594
    595 // Link all the items together
    596 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
    597 return 1; // Error already printed
    598 }
    599
    600 std::auto_ptr Composite(TheLinker.releaseModule());
    601
    602 // Optimize the module
    603 Optimize(Composite.get());
    604
    605 // Generate the bitcode output.
    606 GenerateBitcode(Composite.get(), BitcodeOutputFilename);
    607
    608 // If we are not linking a library, generate either a native executable
    609 // or a JIT shell script, depending upon what the user wants.
    610 if (!LinkAsLibrary) {
    611 // If the user wants to run a post-link optimization, run it now.
    612 if (!PostLinkOpts.empty()) {
    613 std::vector opts = PostLinkOpts;
    614 for (std::vector::iterator I = opts.begin(),
    615 E = opts.end(); I != E; ++I) {
    616 sys::Path prog(*I);
    617 if (!prog.canExecute()) {
    618 prog = sys::Program::FindProgramByName(*I);
    619 if (prog.isEmpty())
    620 PrintAndExit(std::string("Optimization program '") + *I +
    621 "' is not found or not executable.", Composite.get());
    622 }
    623 // Get the program arguments
    624 sys::Path tmp_output("opt_result");
    625 std::string ErrMsg;
    626 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
    627 PrintAndExit(ErrMsg, Composite.get());
    628
    629 const char* args[4];
    630 args[0] = I->c_str();
    631 args[1] = BitcodeOutputFilename.c_str();
    632 args[2] = tmp_output.c_str();
    633 args[3] = 0;
    634 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
    635 if (tmp_output.isBitcodeFile()) {
    636 sys::Path target(BitcodeOutputFilename);
    637 target.eraseFromDisk();
    638 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
    639 PrintAndExit(ErrMsg, Composite.get(), 2);
    640 } else
    641 PrintAndExit("Post-link optimization output is not bitcode",
    642 Composite.get());
    643 } else {
    644 PrintAndExit(ErrMsg, Composite.get());
    645 }
    646 }
    647 }
    648
    649 // If the user wants to generate a native executable, compile it from the
    650 // bitcode file.
    651 //
    652 // Otherwise, create a script that will run the bitcode through the JIT.
    653 if (Native) {
    654 // Name of the Assembly Language output file
    655 sys::Path AssemblyFile ( OutputFilename);
    656 AssemblyFile.appendSuffix("s");
    657
    658 // Mark the output files for removal.
    659 FileRemover AssemblyFileRemover(AssemblyFile.str());
    660 sys::RemoveFileOnSignal(AssemblyFile);
    661
    662 // Determine the locations of the llc and gcc programs.
    663 sys::Path llc = PrependMainExecutablePath("llc", argv[0],
    664 (void *)(intptr_t)&Optimize);
    665 if (llc.isEmpty())
    666 PrintAndExit("Failed to find llc", Composite.get());
    667
    668 sys::Path gcc = sys::Program::FindProgramByName("gcc");
    669 if (gcc.isEmpty())
    670 PrintAndExit("Failed to find gcc", Composite.get());
    671
    672 // Generate an assembly language file for the bitcode.
    673 std::string ErrMsg;
    674 if (0 != GenerateAssembly(AssemblyFile.str(), BitcodeOutputFilename,
    675 llc, ErrMsg))
    676 PrintAndExit(ErrMsg, Composite.get());
    677
    678 if (0 != GenerateNative(OutputFilename, AssemblyFile.str(),
    679 NativeLinkItems, gcc, envp, ErrMsg))
    680 PrintAndExit(ErrMsg, Composite.get());
    681 } else if (NativeCBE) {
    682 sys::Path CFile (OutputFilename);
    683 CFile.appendSuffix("cbe.c");
    684
    685 // Mark the output files for removal.
    686 FileRemover CFileRemover(CFile.str());
    687 sys::RemoveFileOnSignal(CFile);
    688
    689 // Determine the locations of the llc and gcc programs.
    690 sys::Path llc = PrependMainExecutablePath("llc", argv[0],
    691 (void *)(intptr_t)&Optimize);
    692 if (llc.isEmpty())
    693 PrintAndExit("Failed to find llc", Composite.get());
    694
    695 sys::Path gcc = sys::Program::FindProgramByName("gcc");
    696 if (gcc.isEmpty())
    697 PrintAndExit("Failed to find gcc", Composite.get());
    698
    699 // Generate an assembly language file for the bitcode.
    700 std::string ErrMsg;
    701 if (GenerateCFile(CFile.str(), BitcodeOutputFilename, llc, ErrMsg))
    702 PrintAndExit(ErrMsg, Composite.get());
    703
    704 if (GenerateNative(OutputFilename, CFile.str(),
    705 NativeLinkItems, gcc, envp, ErrMsg))
    706 PrintAndExit(ErrMsg, Composite.get());
    707 } else {
    708 EmitShellScript(argv, Composite.get());
    709 }
    710
    711 // Make the script executable...
    712 std::string ErrMsg;
    713 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
    714 PrintAndExit(ErrMsg, Composite.get());
    715
    716 // Make the bitcode file readable and directly executable in LLEE as well
    717 if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
    718 PrintAndExit(ErrMsg, Composite.get());
    719
    720 if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
    721 PrintAndExit(ErrMsg, Composite.get());
    722 }
    723
    724 // Operations which may fail are now complete.
    725 BitcodeOutputRemover.releaseFile();
    726 if (!LinkAsLibrary)
    727 OutputRemover.releaseFile();
    728
    729 // Graceful exit
    730 return 0;
    731 }
    +0
    -3
    tools/llvm-stub/CMakeLists.txt less more
    None add_llvm_tool(llvm-stub
    1 llvm-stub.c
    2 )
    +0
    -22
    tools/llvm-stub/LLVMBuild.txt less more
    None ;===- ./tools/llvm-stub/LLVMBuild.txt --------------------------*- Conf -*--===;
    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 is an LLVMBuild description file for the components in this subdirectory.
    10 ;
    11 ; For more information on the LLVMBuild system, please see:
    12 ;
    13 ; http://llvm.org/docs/LLVMBuild.html
    14 ;
    15 ;===------------------------------------------------------------------------===;
    16
    17 [component_0]
    18 type = Tool
    19 name = llvm-stub
    20 parent = Tools
    21 required_libraries =
    +0
    -15
    tools/llvm-stub/Makefile less more
    None ##===- tools/llvm-stub/Makefile ----------------------------*- Makefile -*-===##
    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 LEVEL := ../..
    10 TOOLNAME := llvm-stub
    11 LINK_COMPONENTS := object
    12
    13 include $(LEVEL)/Makefile.common
    14
    +0
    -77
    tools/llvm-stub/llvm-stub.c less more
    None /*===- llvm-stub.c - Stub executable to run llvm bitcode files ------------===//
    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 tool is used by the gccld program to enable transparent execution of
    10 // bitcode files by the user. Specifically, gccld outputs two files when asked
    11 // to compile a file:
    12 // 1. It outputs the LLVM bitcode file to .bc
    13 // 2. It outputs a stub executable that runs lli on .bc
    14 //
    15 // This allows the end user to just say ./ and have the JIT executed
    16 // automatically. On unix, the stub executable emitted is actually a bourne
    17 // shell script that does the forwarding. Windows does not like #!/bin/sh
    18 // programs in .exe files, so we make it an actual program, defined here.
    19 //
    20 //===----------------------------------------------------------------------===*/
    21
    22 #include
    23 #include
    24 #include
    25
    26 #include "llvm/Config/config.h"
    27
    28 #if defined(HAVE_UNISTD_H) && !defined(_MSC_VER)
    29 #include
    30 #endif
    31
    32 #ifdef _WIN32
    33 #include
    34 #include
    35 #endif
    36
    37 int main(int argc, char** argv) {
    38 const char *Interp = getenv("LLVMINTERP");
    39 const char **Args;
    40 if (Interp == 0) Interp = "lli";
    41
    42 /* Set up the command line options to pass to the JIT. */
    43 Args = (const char**)malloc(sizeof(char*) * (argc+2));
    44 /* argv[0] is the JIT */
    45 Args[0] = Interp;
    46
    47 #ifdef LLVM_ON_WIN32
    48 {
    49 int len = strlen(argv[0]);
    50 if (len < 4 || strcmp(argv[0] + len - 4, ".exe") != 0) {
    51 /* .exe suffix is stripped off of argv[0] if the executable was run on the
    52 * command line without one. Put it back on.
    53 */
    54 argv[0] = strcat(strcpy((char*)malloc(len + 5), argv[0]), ".exe");
    55 }
    56 }
    57 #endif
    58
    59 /* argv[1] is argv[0] + ".bc". */
    60 Args[1] = strcat(strcpy((char*)malloc(strlen(argv[0])+4), argv[0]), ".bc");
    61
    62 /* The rest of the args are as before. */
    63 memcpy((char **)Args+2, argv+1, sizeof(char*)*argc);
    64
    65 /* Run the JIT. */
    66 #if !defined(_WIN32) || defined(__MINGW64__)
    67 execvp(Interp, (char **)Args); /* POSIX execvp takes a char *const[]. */
    68 #else
    69 execvp(Interp, Args); /* windows execvp takes a const char *const *. */
    70 #endif
    71 /* if _execv returns, the JIT could not be started. */
    72 fprintf(stderr, "Could not execute the LLVM JIT. Either add 'lli' to your"
    73 " path, or set the\ninterpreter you want to use in the LLVMINTERP "
    74 "environment variable.\n");
    75 return 1;
    76 }
    7575 # Define the list of optimizations to run. This comprises the same set of
    7676 # optimizations that opt -std-compile-opts and gccld run, in the same order.
    7777 opt_switches=`llvm-as < /dev/null -o - | opt -std-compile-opts -disable-output -debug-pass=Arguments 2>&1 | sed 's/Pass Arguments: //'`
    78 ld_switches=`llvm-as < /dev/null -o - | llvm-ld - -debug-pass=Arguments 2>&1 | sed 's/Pass Arguments: //'`
    79 all_switches="$opt_switches $ld_switches"
    78 all_switches="$opt_switches"
    8079 echo "Passes : $all_switches"
    8180
    8281 # Create output directory if it doesn't exist