Home | History | Annotate | Download | only in llvm-mcld
      1 //===- llvm-mcld.cpp ------------------------------------------------------===//
      2 //
      3 //                     The MCLinker Project
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 #include <mcld/Module.h>
     10 #include <mcld/LinkerConfig.h>
     11 #include <mcld/LinkerScript.h>
     12 #include <mcld/Target/TargetMachine.h>
     13 #include <mcld/Support/TargetSelect.h>
     14 #include <mcld/Support/TargetRegistry.h>
     15 #include <mcld/Support/CommandLine.h>
     16 #include <mcld/Support/Path.h>
     17 #include <mcld/Support/RealPath.h>
     18 #include <mcld/Support/MsgHandling.h>
     19 #include <mcld/Support/FileHandle.h>
     20 #include <mcld/Support/FileSystem.h>
     21 #include <mcld/Support/raw_ostream.h>
     22 #include <mcld/Support/SystemUtils.h>
     23 #include <mcld/Support/ToolOutputFile.h>
     24 #include <mcld/LD/DiagnosticLineInfo.h>
     25 #include <mcld/LD/TextDiagnosticPrinter.h>
     26 
     27 #include <llvm/PassManager.h>
     28 #include <llvm/Pass.h>
     29 #include <llvm/IR/Module.h>
     30 #include <llvm/IR/DataLayout.h>
     31 #include <llvm/IR/LLVMContext.h>
     32 #include <llvm/ADT/Triple.h>
     33 #include <llvm/ADT/StringSwitch.h>
     34 #include <llvm/MC/SubtargetFeature.h>
     35 #include <llvm/Support/CommandLine.h>
     36 #include <llvm/Support/Debug.h>
     37 #include <llvm/Support/FormattedStream.h>
     38 #include <llvm/Support/Host.h>
     39 #include <llvm/Support/IRReader.h>
     40 #include <llvm/Support/ManagedStatic.h>
     41 #include <llvm/Support/Signals.h>
     42 #include <llvm/Support/TargetRegistry.h>
     43 #include <llvm/Support/TargetSelect.h>
     44 #include <llvm/Support/Process.h>
     45 #include <llvm/Target/TargetMachine.h>
     46 
     47 #if defined(HAVE_UNISTD_H)
     48 # include <unistd.h>
     49 #endif
     50 
     51 #if defined(_MSC_VER) || defined(__MINGW32__)
     52 #include <io.h>
     53 #ifndef STDIN_FILENO
     54 # define STDIN_FILENO 0
     55 #endif
     56 #ifndef STDOUT_FILENO
     57 # define STDOUT_FILENO 1
     58 #endif
     59 #ifndef STDERR_FILENO
     60 # define STDERR_FILENO 2
     61 #endif
     62 #endif
     63 
     64 using namespace llvm;
     65 
     66 #ifdef ENABLE_UNITTEST
     67 #include <gtest.h>
     68 
     69 static cl::opt<bool>
     70 UnitTest("unittest",  cl::desc("do unit test") );
     71 
     72 int unit_test( int argc, char* argv[] )
     73 {
     74   testing::InitGoogleTest( &argc, argv );
     75   return RUN_ALL_TESTS();
     76 }
     77 
     78 #endif
     79 
     80 // General options for llc.  Other pass-specific options are specified
     81 // within the corresponding llc passes, and target-specific options
     82 // and back-end code generation options are specified with the target machine.
     83 //
     84 // Determine optimization level.
     85 static cl::opt<char>
     86 OptLevel("O",
     87          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
     88                   "(default = '-O2')"),
     89          cl::Prefix,
     90          cl::ZeroOrMore,
     91          cl::init(' '));
     92 
     93 static cl::opt<std::string>
     94 TargetTriple("mtriple", cl::desc("Override target triple for module"));
     95 
     96 static cl::opt<std::string>
     97 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
     98 
     99 static cl::opt<std::string>
    100 MCPU("mcpu",
    101   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
    102   cl::value_desc("cpu-name"),
    103   cl::init(""));
    104 
    105 static cl::list<std::string>
    106 MAttrs("mattr",
    107   cl::CommaSeparated,
    108   cl::desc("Target specific attributes (-mattr=help for details)"),
    109   cl::value_desc("a1,+a2,-a3,..."));
    110 
    111 static cl::opt<llvm::CodeModel::Model>
    112 CMModel("code-model",
    113         cl::desc("Choose code model"),
    114         cl::init(CodeModel::Default),
    115         cl::values(clEnumValN(CodeModel::Default, "default",
    116                               "Target default code model"),
    117                    clEnumValN(CodeModel::Small, "small",
    118                               "Small code model"),
    119                    clEnumValN(CodeModel::Kernel, "kernel",
    120                               "Kernel code model"),
    121                    clEnumValN(CodeModel::Medium, "medium",
    122                               "Medium code model"),
    123                    clEnumValN(CodeModel::Large, "large",
    124                               "Large code model"),
    125                    clEnumValEnd));
    126 
    127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
    128                        cl::desc("Do not verify input module"));
    129 
    130 static cl::opt<bool>
    131 EnableFPMAD("enable-fp-mad",
    132   cl::desc("Enable less precise MAD instructions to be generated"),
    133   cl::init(false));
    134 
    135 static cl::opt<bool>
    136 DisableFPElim("disable-fp-elim",
    137   cl::desc("Disable frame pointer elimination optimization"),
    138   cl::init(false));
    139 
    140 static cl::opt<bool>
    141 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
    142   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
    143   cl::init(false));
    144 
    145 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
    146 FuseFPOps("fuse-fp-ops",
    147   cl::desc("Enable aggresive formation of fused FP ops"),
    148   cl::init(FPOpFusion::Standard),
    149   cl::values(
    150     clEnumValN(FPOpFusion::Fast, "fast",
    151                "Fuse FP ops whenever profitable"),
    152     clEnumValN(FPOpFusion::Standard, "standard",
    153                "Only fuse 'blessed' FP ops."),
    154     clEnumValN(FPOpFusion::Strict, "strict",
    155                "Only fuse FP ops when the result won't be effected."),
    156     clEnumValEnd));
    157 
    158 static cl::opt<bool>
    159 EnableUnsafeFPMath("enable-unsafe-fp-math",
    160   cl::desc("Enable optimizations that may decrease FP precision"),
    161   cl::init(false));
    162 
    163 static cl::opt<bool>
    164 EnableNoInfsFPMath("enable-no-infs-fp-math",
    165   cl::desc("Enable FP math optimizations that assume no +-Infs"),
    166   cl::init(false));
    167 
    168 static cl::opt<bool>
    169 EnableNoNaNsFPMath("enable-no-nans-fp-math",
    170   cl::desc("Enable FP math optimizations that assume no NaNs"),
    171   cl::init(false));
    172 
    173 static cl::opt<bool>
    174 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
    175   cl::Hidden,
    176   cl::desc("Force codegen to assume rounding mode can change dynamically"),
    177   cl::init(false));
    178 
    179 static cl::opt<bool>
    180 GenerateSoftFloatCalls("soft-float",
    181   cl::desc("Generate software floating point library calls"),
    182   cl::init(false));
    183 
    184 static cl::opt<llvm::FloatABI::ABIType>
    185 FloatABIForCalls("float-abi",
    186   cl::desc("Choose float ABI type"),
    187   cl::init(FloatABI::Default),
    188   cl::values(
    189     clEnumValN(FloatABI::Default, "default",
    190                "Target default float ABI type"),
    191     clEnumValN(FloatABI::Soft, "soft",
    192                "Soft float ABI (implied by -soft-float)"),
    193     clEnumValN(FloatABI::Hard, "hard",
    194                "Hard float ABI (uses FP registers)"),
    195     clEnumValEnd));
    196 
    197 static cl::opt<bool>
    198 DontPlaceZerosInBSS("nozero-initialized-in-bss",
    199   cl::desc("Don't place zero-initialized symbols into bss section"),
    200   cl::init(false));
    201 
    202 static cl::opt<bool>
    203 EnableJITExceptionHandling("jit-enable-eh",
    204   cl::desc("Emit exception handling information"),
    205   cl::init(false));
    206 
    207 // In debug builds, make this default to true.
    208 #ifdef NDEBUG
    209 #define EMIT_DEBUG false
    210 #else
    211 #define EMIT_DEBUG true
    212 #endif
    213 static cl::opt<bool>
    214 EmitJitDebugInfo("jit-emit-debug",
    215   cl::desc("Emit debug information to debugger"),
    216   cl::init(EMIT_DEBUG));
    217 #undef EMIT_DEBUG
    218 
    219 static cl::opt<bool>
    220 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
    221   cl::Hidden,
    222   cl::desc("Emit debug info objfiles to disk"),
    223   cl::init(false));
    224 
    225 static cl::opt<bool>
    226 EnableGuaranteedTailCallOpt("tailcallopt",
    227   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
    228   cl::init(false));
    229 
    230 static cl::opt<unsigned>
    231 OverrideStackAlignment("stack-alignment",
    232   cl::desc("Override default stack alignment"),
    233   cl::init(0));
    234 
    235 static cl::opt<bool>
    236 EnableRealignStack("realign-stack",
    237   cl::desc("Realign stack if needed"),
    238   cl::init(true));
    239 
    240 static cl::opt<std::string>
    241 TrapFuncName("trap-func", cl::Hidden,
    242   cl::desc("Emit a call to trap function rather than a trap instruction"),
    243   cl::init(""));
    244 
    245 static cl::opt<bool>
    246 SegmentedStacks("segmented-stacks",
    247   cl::desc("Use segmented stacks if possible."),
    248   cl::init(false));
    249 
    250 //===----------------------------------------------------------------------===//
    251 // Command Line Options
    252 // There are four kinds of command line options:
    253 //   1. Bitcode option. Used to represent a bitcode.
    254 //   2. Attribute options. Attributes describes the input file after them. For
    255 //      example, --as-needed affects the input file after this option. Attribute
    256 //      options are not attributes. Attribute options are the options that is
    257 //      used to define a legal attribute.
    258 //   3. Scripting options, Used to represent a subset of link scripting
    259 //      language, such as --defsym.
    260 //   4. General options. (the rest of options)
    261 //===----------------------------------------------------------------------===//
    262 // Bitcode Options
    263 //===----------------------------------------------------------------------===//
    264 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
    265 ArgBitcodeFilename("dB",
    266               cl::desc("set default bitcode"),
    267               cl::value_desc("bitcode"));
    268 
    269 //===----------------------------------------------------------------------===//
    270 // General Options
    271 //===----------------------------------------------------------------------===//
    272 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
    273 ArgOutputFilename("o",
    274                cl::desc("Output filename"),
    275                cl::value_desc("filename"));
    276 
    277 static cl::alias
    278 AliasOutputFilename("output",
    279                     cl::desc("alias for -o"),
    280                     cl::aliasopt(ArgOutputFilename));
    281 
    282 static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
    283 ArgSysRoot("sysroot",
    284            cl::desc("Use directory as the location of the sysroot, overriding the configure-time default."),
    285            cl::value_desc("directory"),
    286            cl::ValueRequired);
    287 
    288 static cl::list<std::string, bool, llvm::cl::SearchDirParser>
    289 ArgSearchDirList("L",
    290                  cl::ZeroOrMore,
    291                  cl::desc("Add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts."),
    292                  cl::value_desc("searchdir"),
    293                  cl::Prefix);
    294 
    295 static cl::alias
    296 ArgSearchDirListAlias("library-path",
    297                       cl::desc("alias for -L"),
    298                       cl::aliasopt(ArgSearchDirList));
    299 
    300 static cl::opt<bool>
    301 ArgTrace("t",
    302          cl::desc("Print the names of the input files as ld processes them."));
    303 
    304 static cl::alias
    305 ArgTraceAlias("trace",
    306               cl::desc("alias for -t"),
    307               cl::aliasopt(ArgTrace));
    308 
    309 static cl::opt<int>
    310 ArgVerbose("verbose",
    311            cl::init(-1),
    312            cl::desc("Display the version number for ld and list the linker emulations supported."));
    313 
    314 static cl::opt<bool>
    315 ArgVersion("V",
    316            cl::init(false),
    317            cl::desc("Display the version number for MCLinker."));
    318 
    319 static cl::opt<int>
    320 ArgMaxErrorNum("error-limit",
    321                cl::init(-1),
    322                cl::desc("limits the maximum number of erros."));
    323 
    324 static cl::opt<int>
    325 ArgMaxWarnNum("warning-limit",
    326                cl::init(-1),
    327                cl::desc("limits the maximum number of warnings."));
    328 
    329 static cl::opt<std::string>
    330 ArgEntry("e",
    331          cl::desc("Use entry as the explicit symbol for beginning execution of your program."),
    332          cl::value_desc("entry"),
    333          cl::ValueRequired);
    334 
    335 static cl::alias
    336 ArgEntryAlias("entry",
    337               cl::desc("alias for -e"),
    338               cl::aliasopt(ArgEntry));
    339 
    340 static cl::opt<bool>
    341 ArgBsymbolic("Bsymbolic",
    342              cl::desc("Bind references within the shared library."),
    343              cl::init(false));
    344 
    345 static cl::opt<bool>
    346 ArgBgroup("Bgroup",
    347           cl::desc("Info the dynamic linker to perform lookups only inside the group."),
    348           cl::init(false));
    349 
    350 static cl::opt<std::string>
    351 ArgSOName("soname",
    352           cl::desc("Set internal name of shared library"),
    353           cl::value_desc("name"));
    354 
    355 static cl::opt<bool>
    356 ArgNoUndefined("no-undefined",
    357                cl::desc("Do not allow unresolved references"),
    358                cl::init(false));
    359 
    360 static cl::opt<bool>
    361 ArgAllowMulDefs("allow-multiple-definition",
    362                 cl::desc("Allow multiple definition"),
    363                 cl::init(false));
    364 
    365 static cl::opt<bool>
    366 ArgEhFrameHdr("eh-frame-hdr",
    367               cl::desc("Request creation of \".eh_frame_hdr\" section and ELF \"PT_GNU_EH_FRAME\" segment header."),
    368               cl::init(false));
    369 
    370 static cl::list<mcld::ZOption, bool, llvm::cl::parser<mcld::ZOption> >
    371 ArgZOptionList("z",
    372                cl::ZeroOrMore,
    373                cl::desc("The -z options for GNU ld compatibility."),
    374                cl::value_desc("keyword"),
    375                cl::Prefix);
    376 
    377 cl::opt<mcld::CodeGenFileType>
    378 ArgFileType("filetype", cl::init(mcld::CGFT_EXEFile),
    379   cl::desc("Choose a file type (not all types are supported by all targets):"),
    380   cl::values(
    381        clEnumValN(mcld::CGFT_ASMFile, "asm",
    382                   "Emit an assembly ('.s') file"),
    383        clEnumValN(mcld::CGFT_OBJFile, "obj",
    384                   "Emit a relocatable object ('.o') file"),
    385        clEnumValN(mcld::CGFT_DSOFile, "dso",
    386                   "Emit an dynamic shared object ('.so') file"),
    387        clEnumValN(mcld::CGFT_EXEFile, "exe",
    388                   "Emit a executable ('.exe') file"),
    389        clEnumValN(mcld::CGFT_NULLFile, "null",
    390                   "Emit nothing, for performance testing"),
    391        clEnumValEnd));
    392 
    393 static cl::opt<bool>
    394 ArgShared("shared",
    395           cl::desc("Create a shared library."),
    396           cl::init(false));
    397 
    398 static cl::alias
    399 ArgSharedAlias("Bshareable",
    400                cl::desc("alias for -shared"),
    401                cl::aliasopt(ArgShared));
    402 
    403 static cl::opt<bool>
    404 ArgPIE("pie",
    405        cl::desc("Emit a position-independent executable file"),
    406        cl::init(false));
    407 
    408 static cl::opt<bool>
    409 ArgRelocatable("relocatable",
    410                cl::desc("Generate relocatable output"),
    411                cl::init(false));
    412 
    413 static cl::alias
    414 ArgRelocatableAlias("r",
    415                     cl::desc("alias for --relocatable"),
    416                     cl::aliasopt(ArgRelocatable));
    417 
    418 static cl::opt<Reloc::Model>
    419 ArgRelocModel("relocation-model",
    420              cl::desc("Choose relocation model"),
    421              cl::init(Reloc::Default),
    422              cl::values(
    423                clEnumValN(Reloc::Default, "default",
    424                        "Target default relocation model"),
    425                clEnumValN(Reloc::Static, "static",
    426                        "Non-relocatable code"),
    427                clEnumValN(Reloc::PIC_, "pic",
    428                        "Fully relocatable, position independent code"),
    429                clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
    430                        "Relocatable external references, non-relocatable code"),
    431                clEnumValEnd));
    432 
    433 static cl::opt<bool>
    434 ArgFPIC("fPIC",
    435         cl::desc("Set relocation model to pic. The same as -relocation-model=pic."),
    436         cl::init(false));
    437 
    438 static cl::opt<std::string>
    439 ArgDyld("dynamic-linker",
    440         cl::ZeroOrMore,
    441         cl::desc("Set the name of the dynamic linker."),
    442         cl::value_desc("Program"));
    443 
    444 namespace color {
    445 enum Color {
    446   Never,
    447   Always,
    448   Auto
    449 };
    450 } // namespace of color
    451 
    452 static cl::opt<color::Color>
    453 ArgColor("color",
    454   cl::value_desc("WHEN"),
    455   cl::desc("Surround the result strings with the marker"),
    456   cl::init(color::Auto),
    457   cl::values(
    458     clEnumValN(color::Never, "never",
    459       "do not surround result strings"),
    460     clEnumValN(color::Always, "always",
    461       "always surround result strings, even the output is a plain file"),
    462     clEnumValN(color::Auto, "auto",
    463       "surround result strings only if the output is a tty"),
    464     clEnumValEnd));
    465 
    466 static cl::opt<bool>
    467 ArgDiscardLocals("discard-locals",
    468                  cl::desc("Delete all temporary local symbols."),
    469                  cl::init(false));
    470 
    471 static cl::alias
    472 ArgDiscardLocalsAlias("X",
    473                       cl::desc("alias for --discard-locals"),
    474                       cl::aliasopt(ArgDiscardLocals));
    475 
    476 static cl::opt<bool>
    477 ArgDiscardAll("discard-all",
    478               cl::desc("Delete all local symbols."),
    479               cl::init(false));
    480 
    481 static cl::alias
    482 ArgDiscardAllAlias("x",
    483                    cl::desc("alias for --discard-all"),
    484                    cl::aliasopt(ArgDiscardAll));
    485 
    486 static cl::opt<bool>
    487 ArgStripDebug("strip-debug",
    488               cl::desc("Omit debugger symbol information from the output file."),
    489               cl::init(false));
    490 
    491 static cl::alias
    492 ArgStripDebugAlias("S",
    493                    cl::desc("alias for --strip-debug"),
    494                    cl::aliasopt(ArgStripDebug));
    495 
    496 static cl::opt<bool>
    497 ArgStripAll("strip-all",
    498             cl::desc("Omit all symbol information from the output file."),
    499             cl::init(false));
    500 
    501 static cl::alias
    502 ArgStripAllAlias("s",
    503                  cl::desc("alias for --strip-all"),
    504                  cl::aliasopt(ArgStripAll));
    505 
    506 static cl::opt<bool>
    507 ArgNMagic("nmagic",
    508           cl::desc("Do not page align data"),
    509           cl::init(false));
    510 
    511 static cl::alias
    512 ArgNMagicAlias("n",
    513                cl::desc("alias for --nmagic"),
    514                cl::aliasopt(ArgNMagic));
    515 
    516 static cl::opt<bool>
    517 ArgOMagic("omagic",
    518           cl::desc("Do not page align data, do not make text readonly"),
    519           cl::init(false));
    520 
    521 static cl::alias
    522 ArgOMagicAlias("N",
    523                cl::desc("alias for --omagic"),
    524                cl::aliasopt(ArgOMagic));
    525 
    526 
    527 static cl::opt<int>
    528 ArgGPSize("G",
    529           cl::desc("Set the maximum size of objects to be optimized using GP"),
    530           cl::init(8));
    531 
    532 /// @{
    533 /// @name FIXME: begin of unsupported options
    534 /// @}
    535 static cl::opt<bool>
    536 ArgGCSections("gc-sections",
    537               cl::desc("Enable garbage collection of unused input sections."),
    538               cl::init(false));
    539 
    540 static cl::opt<bool>
    541 ArgNoGCSections("no-gc-sections",
    542               cl::desc("disable garbage collection of unused input sections."),
    543               cl::init(false));
    544 
    545 namespace icf {
    546 enum Mode {
    547   None,
    548   All,
    549   Safe
    550 };
    551 } // namespace of icf
    552 
    553 static cl::opt<icf::Mode>
    554 ArgICF("icf",
    555        cl::ZeroOrMore,
    556        cl::desc("Identical Code Folding"),
    557        cl::init(icf::None),
    558        cl::values(
    559          clEnumValN(icf::None, "none",
    560            "do not perform cold folding"),
    561          clEnumValN(icf::All, "all",
    562            "always preform cold folding"),
    563          clEnumValN(icf::Safe, "safe",
    564            "Folds ctors, dtors and functions whose pointers are definitely not taken."),
    565          clEnumValEnd));
    566 
    567 // FIXME: add this to target options?
    568 static cl::opt<bool>
    569 ArgFIXCA8("fix-cortex-a8",
    570           cl::desc("Enable Cortex-A8 Thumb-2 branch erratum fix"),
    571           cl::init(false));
    572 
    573 static cl::opt<bool>
    574 ArgExportDynamic("export-dynamic",
    575                  cl::desc("Export all dynamic symbols"),
    576                  cl::init(false));
    577 
    578 static cl::alias
    579 ArgExportDynamicAlias("E",
    580                       cl::desc("alias for --export-dynamic"),
    581                       cl::aliasopt(ArgExportDynamic));
    582 
    583 static cl::opt<std::string>
    584 ArgEmulation("m",
    585              cl::ZeroOrMore,
    586              cl::desc("Set GNU linker emulation"),
    587              cl::value_desc("emulation"));
    588 
    589 static cl::list<std::string, bool, llvm::cl::SearchDirParser>
    590 ArgRuntimePathLink("rpath-link",
    591                    cl::ZeroOrMore,
    592                    cl::desc("Add a directory to the link time library search path"),
    593                    cl::value_desc("dir"));
    594 
    595 static cl::list<std::string>
    596 ArgExcludeLIBS("exclude-libs",
    597                cl::CommaSeparated,
    598                cl::desc("Exclude libraries from automatic export"),
    599                cl::value_desc("lib1,lib2,..."));
    600 
    601 static cl::opt<std::string>
    602 ArgBuildID("build-id",
    603            cl::desc("Request creation of \".note.gnu.build-id\" ELF note section."),
    604            cl::value_desc("style"),
    605            cl::ValueOptional);
    606 
    607 static cl::opt<std::string>
    608 ArgForceUndefined("u",
    609                   cl::desc("Force symbol to be undefined in the output file"),
    610                   cl::value_desc("symbol"));
    611 
    612 static cl::alias
    613 ArgForceUndefinedAlias("undefined",
    614                        cl::desc("alias for -u"),
    615                        cl::aliasopt(ArgForceUndefined));
    616 
    617 static cl::opt<std::string>
    618 ArgVersionScript("version-script",
    619                  cl::desc("Version script."),
    620                  cl::value_desc("Version script"));
    621 
    622 static cl::opt<bool>
    623 ArgWarnCommon("warn-common",
    624               cl::desc("warn common symbol"),
    625               cl::init(false));
    626 
    627 static cl::opt<mcld::GeneralOptions::HashStyle>
    628 ArgHashStyle("hash-style", cl::init(mcld::GeneralOptions::SystemV),
    629   cl::desc("Set the type of linker's hash table(s)."),
    630   cl::values(
    631        clEnumValN(mcld::GeneralOptions::SystemV, "sysv",
    632                  "classic ELF .hash section"),
    633        clEnumValN(mcld::GeneralOptions::GNU, "gnu",
    634                  "new style GNU .gnu.hash section"),
    635        clEnumValN(mcld::GeneralOptions::Both, "both",
    636                  "both the classic ELF and new style GNU hash tables"),
    637        clEnumValEnd));
    638 
    639 static cl::opt<std::string>
    640 ArgFilter("F",
    641           cl::desc("Filter for shared object symbol table"),
    642           cl::value_desc("name"));
    643 
    644 static cl::alias
    645 ArgFilterAlias("filter",
    646                cl::desc("alias for -F"),
    647                cl::aliasopt(ArgFilterAlias));
    648 
    649 static cl::list<std::string>
    650 ArgAuxiliary("f",
    651              cl::ZeroOrMore,
    652              cl::desc("Auxiliary filter for shared object symbol table"),
    653              cl::value_desc("name"));
    654 
    655 static cl::alias
    656 ArgAuxiliaryAlias("auxiliary",
    657                   cl::desc("alias for -f"),
    658                   cl::aliasopt(ArgAuxiliary));
    659 
    660 static cl::opt<bool>
    661 ArgUseGold("use-gold",
    662           cl::desc("GCC/collect2 compatibility: uses ld.gold.  Ignored"),
    663           cl::init(false));
    664 
    665 static cl::opt<bool>
    666 ArgUseMCLD("use-mcld",
    667           cl::desc("GCC/collect2 compatibility: uses ld.mcld.  Ignored"),
    668           cl::init(false));
    669 
    670 static cl::opt<bool>
    671 ArgUseLD("use-ld",
    672           cl::desc("GCC/collect2 compatibility: uses ld.bfd.  Ignored"),
    673           cl::init(false));
    674 
    675 static cl::opt<bool>
    676 ArgEB("EB",
    677       cl::desc("Link big-endian objects. This affects the default output format."),
    678       cl::init(false));
    679 
    680 static cl::opt<bool>
    681 ArgEL("EL",
    682       cl::desc("Link little-endian objects. This affects the default output format."),
    683       cl::init(false));
    684 
    685 static cl::list<std::string>
    686 ArgPlugin("plugin",
    687           cl::desc("Load a plugin library."),
    688           cl::value_desc("plugin"));
    689 
    690 static cl::list<std::string>
    691 ArgPluginOpt("plugin-opt",
    692              cl::desc("	Pass an option to the plugin."),
    693              cl::value_desc("option"));
    694 
    695 static cl::opt<bool>
    696 ArgSVR4Compatibility("Qy",
    697                     cl::desc("This option is ignored for SVR4 compatibility"),
    698                     cl::init(false));
    699 
    700 static cl::list<std::string>
    701 ArgY("Y",
    702      cl::desc("Add path to the default library search path"),
    703      cl::value_desc("default-search-path"));
    704 
    705 /// @{
    706 /// @name FIXME: end of unsupported options
    707 /// @}
    708 
    709 static cl::opt<bool>
    710 ArgNoStdlib("nostdlib",
    711             cl::desc("Only search lib dirs explicitly specified on cmdline"),
    712             cl::init(false));
    713 
    714 static cl::list<std::string, bool, llvm::cl::SearchDirParser>
    715 ArgRuntimePath("rpath",
    716                cl::ZeroOrMore,
    717                cl::desc("Add a directory to the runtime library search path"),
    718                cl::value_desc("dir"));
    719 
    720 static cl::alias
    721 ArgRuntimePathAlias("R",
    722                     cl::desc("alias for --rpath"),
    723                     cl::aliasopt(ArgRuntimePath), cl::Prefix);
    724 
    725 static cl::opt<bool>
    726 ArgEnableNewDTags("enable-new-dtags",
    727                   cl::desc("Enable use of DT_RUNPATH and DT_FLAGS"),
    728                   cl::init(false));
    729 
    730 static cl::opt<bool>
    731 ArgPrintMap("M",
    732             cl::desc("Print a link map to the standard output."),
    733             cl::init(false));
    734 
    735 static cl::alias
    736 ArgPrintMapAlias("print-map",
    737                  cl::desc("alias for -M"),
    738                  cl::aliasopt(ArgPrintMap));
    739 
    740 static bool ArgFatalWarnings;
    741 
    742 static cl::opt<bool, true, cl::FalseParser>
    743 ArgNoFatalWarnings("no-fatal-warnings",
    744               cl::location(ArgFatalWarnings),
    745               cl::desc("do not turn warnings into errors"),
    746               cl::init(false),
    747               cl::ValueDisallowed);
    748 
    749 static cl::opt<bool, true>
    750 ArgFatalWarningsFlag("fatal-warnings",
    751               cl::location(ArgFatalWarnings),
    752               cl::desc("turn all warnings into errors"),
    753               cl::init(false),
    754               cl::ValueDisallowed);
    755 
    756 static cl::opt<bool>
    757 ArgWarnSharedTextrel("warn-shared-textrel",
    758                      cl::desc("Warn if adding DT_TEXTREL in a shared object."),
    759                      cl::init(false));
    760 
    761 namespace format {
    762 enum Format {
    763   Binary,
    764   Unknown // decided by triple
    765 };
    766 } // namespace of format
    767 
    768 static cl::opt<format::Format>
    769 ArgFormat("b",
    770   cl::value_desc("Format"),
    771   cl::desc("set input format"),
    772   cl::init(format::Unknown),
    773   cl::values(
    774     clEnumValN(format::Binary, "binary",
    775       "read in binary machine code."),
    776     clEnumValEnd));
    777 
    778 static cl::alias
    779 ArgFormatAlias("format",
    780                cl::desc("alias for -b"),
    781                cl::aliasopt(ArgFormat));
    782 
    783 static cl::opt<format::Format>
    784 ArgOFormat("oformat",
    785   cl::value_desc("Format"),
    786   cl::desc("set output format"),
    787   cl::init(format::Unknown),
    788   cl::values(
    789     clEnumValN(format::Binary, "binary",
    790       "generate binary machine code."),
    791     clEnumValEnd));
    792 
    793 static cl::opt<bool>
    794 ArgDefineCommon("d",
    795                 cl::ZeroOrMore,
    796                 cl::desc("Define common symbol"),
    797                 cl::init(false));
    798 
    799 static cl::alias
    800 ArgDefineCommonAlias1("dc",
    801                       cl::ZeroOrMore,
    802                       cl::desc("alias for -d"),
    803                       cl::aliasopt(ArgDefineCommon));
    804 
    805 static cl::alias
    806 ArgDefineCommonAlias2("dp",
    807                       cl::ZeroOrMore,
    808                       cl::desc("alias for -d"),
    809                       cl::aliasopt(ArgDefineCommon));
    810 
    811 //===----------------------------------------------------------------------===//
    812 // Scripting Options
    813 //===----------------------------------------------------------------------===//
    814 static cl::list<std::string>
    815 ArgWrapList("wrap",
    816             cl::ZeroOrMore,
    817             cl::desc("Use a wrap function fo symbol."),
    818             cl::value_desc("symbol"));
    819 
    820 static cl::list<std::string>
    821 ArgPortList("portable",
    822             cl::ZeroOrMore,
    823             cl::desc("Use a portable function fo symbol."),
    824             cl::value_desc("symbol"));
    825 
    826 static cl::list<std::string>
    827 ArgAddressMapList("section-start",
    828                   cl::ZeroOrMore,
    829                   cl::desc("Locate a output section at the given absolute address"),
    830                   cl::value_desc("Set address of section"),
    831                   cl::Prefix);
    832 
    833 static cl::list<std::string>
    834 ArgDefSymList("defsym",
    835               cl::ZeroOrMore,
    836               cl::desc("Define a symbol"),
    837               cl::value_desc("symbol=expression"));
    838 
    839 static cl::opt<unsigned long long>
    840 ArgBssSegAddr("Tbss",
    841               cl::desc("Set the address of the bss segment"),
    842               cl::init(-1U));
    843 
    844 static cl::opt<unsigned long long>
    845 ArgDataSegAddr("Tdata",
    846                cl::desc("Set the address of the data segment"),
    847                cl::init(-1U));
    848 
    849 static cl::opt<unsigned long long>
    850 ArgTextSegAddr("Ttext",
    851                cl::desc("Set the address of the text segment"),
    852                cl::init(-1U));
    853 
    854 //===----------------------------------------------------------------------===//
    855 // non-member functions
    856 //===----------------------------------------------------------------------===//
    857 /// GetOutputStream - get the output stream.
    858 static mcld::ToolOutputFile *GetOutputStream(const char* pTargetName,
    859                                              Triple::OSType pOSType,
    860                                              mcld::CodeGenFileType pFileType,
    861                                              const mcld::sys::fs::Path& pInputFilename,
    862                                              mcld::sys::fs::Path& pOutputFilename)
    863 {
    864   if (pOutputFilename.empty()) {
    865     if (0 == pInputFilename.native().compare("-"))
    866       pOutputFilename.assign("-");
    867     else {
    868       switch(pFileType) {
    869       case mcld::CGFT_ASMFile: {
    870         if (0 == pInputFilename.native().compare("-"))
    871           pOutputFilename.assign("_out");
    872         else
    873           pOutputFilename.assign(pInputFilename.stem().native());
    874 
    875         if (0 == strcmp(pTargetName, "c"))
    876           pOutputFilename.native() += ".cbe.c";
    877         else if (0 == strcmp(pTargetName, "cpp"))
    878           pOutputFilename.native() += ".cpp";
    879         else
    880           pOutputFilename.native() += ".s";
    881       }
    882       break;
    883 
    884       case mcld::CGFT_OBJFile: {
    885         if (0 == pInputFilename.native().compare("-"))
    886           pOutputFilename.assign("_out");
    887         else
    888           pOutputFilename.assign(pInputFilename.stem().native());
    889 
    890         if (pOSType == Triple::Win32)
    891           pOutputFilename.native() += ".obj";
    892         else
    893           pOutputFilename.native() += ".o";
    894       }
    895       break;
    896 
    897       case mcld::CGFT_PARTIAL: {
    898         if (Triple::Win32 == pOSType) {
    899           if (0 == pInputFilename.native().compare("-"))
    900             pOutputFilename.assign("_out");
    901           else
    902             pOutputFilename.assign(pInputFilename.stem().native());
    903           pOutputFilename.native() += ".obj";
    904         }
    905         else
    906           pOutputFilename.assign("a.out");
    907       }
    908       break;
    909 
    910       case mcld::CGFT_DSOFile: {
    911         if (Triple::Win32 == pOSType) {
    912           if (0 == pInputFilename.native().compare("-"))
    913             pOutputFilename.assign("_out");
    914           else
    915             pOutputFilename.assign(pInputFilename.stem().native());
    916           pOutputFilename.native() += ".dll";
    917         }
    918         else
    919           pOutputFilename.assign("a.out");
    920       }
    921       break;
    922 
    923       case mcld::CGFT_EXEFile: {
    924         if (Triple::Win32 == pOSType) {
    925           if (0 == pInputFilename.native().compare("-"))
    926             pOutputFilename.assign("_out");
    927           else
    928             pOutputFilename.assign(pInputFilename.stem().native());
    929           pOutputFilename.native() += ".exe";
    930         }
    931         else
    932           pOutputFilename.assign("a.out");
    933       }
    934       break;
    935 
    936       case mcld::CGFT_NULLFile:
    937         break;
    938       default:
    939         llvm::report_fatal_error("Unknown output file type.\n");
    940       } // end of switch
    941     } // end of ! pInputFilename == "-"
    942   } // end of if empty pOutputFilename
    943 
    944   mcld::FileHandle::Permission permission;
    945   switch (pFileType) {
    946   default: assert(0 && "Unknown file type");
    947   case mcld::CGFT_ASMFile:
    948   case mcld::CGFT_OBJFile:
    949   case mcld::CGFT_PARTIAL:
    950     permission = mcld::FileHandle::Permission(0x644);
    951     break;
    952   case mcld::CGFT_DSOFile:
    953   case mcld::CGFT_EXEFile:
    954   case mcld::CGFT_BINARY:
    955   case mcld::CGFT_NULLFile:
    956     permission = mcld::FileHandle::Permission(0x755);
    957     break;
    958   }
    959 
    960   // Open the file.
    961   mcld::ToolOutputFile* result_output =
    962                       new mcld::ToolOutputFile(pOutputFilename,
    963                                                  mcld::FileHandle::ReadWrite |
    964                                                  mcld::FileHandle::Create |
    965                                                  mcld::FileHandle::Truncate,
    966                                                permission);
    967 
    968   return result_output;
    969 }
    970 
    971 /// ParseProgName - Parse program name
    972 /// This function simplifies cross-compiling by reading triple from the program
    973 /// name. For example, if the program name is `arm-linux-eabi-ld.mcld', we can
    974 /// get the triple is arm-linux-eabi by the program name.
    975 static std::string ParseProgName(const char *progname)
    976 {
    977   static const char *suffixes[] = {
    978     "ld",
    979     "ld.mcld",
    980   };
    981 
    982   std::string ProgName(mcld::sys::fs::Path(progname).stem().native());
    983 
    984   for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
    985     if (ProgName == suffixes[i])
    986       return std::string();
    987   }
    988 
    989   StringRef ProgNameRef(ProgName);
    990   StringRef Prefix;
    991 
    992   for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
    993     if (!ProgNameRef.endswith(suffixes[i]))
    994       continue;
    995 
    996     StringRef::size_type LastComponent = ProgNameRef.rfind('-',
    997       ProgNameRef.size() - strlen(suffixes[i]));
    998     if (LastComponent == StringRef::npos)
    999       continue;
   1000     StringRef Prefix = ProgNameRef.slice(0, LastComponent);
   1001     std::string IgnoredError;
   1002     if (!llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError))
   1003       continue;
   1004     return Prefix.str();
   1005   }
   1006   return std::string();
   1007 }
   1008 
   1009 static Triple ParseEmulation(const std::string& pEmulation)
   1010 {
   1011   Triple result = StringSwitch<Triple>(pEmulation)
   1012     .Case("armelf_linux_eabi", Triple("arm", "", "linux", "gnueabi"))
   1013     .Case("elf_i386",          Triple("i386", "", "", "gnu"))
   1014     .Case("elf_x86_64",        Triple("x86_64", "", "", "gnu"))
   1015     .Case("elf32_x86_64",      Triple("x86_64", "", "", "gnux32"))
   1016     .Case("elf_i386_fbsd",     Triple("i386", "", "freebsd", "gnu"))
   1017     .Case("elf_x86_64_fbsd",   Triple("x86_64", "", "freebsd", "gnu"))
   1018     .Case("elf32ltsmip",       Triple("mipsel", "", "", "gnu"))
   1019     .Default(Triple());
   1020 
   1021   if (result.getArch()        == Triple::UnknownArch &&
   1022       result.getOS()          == Triple::UnknownOS &&
   1023       result.getEnvironment() == Triple::UnknownEnvironment)
   1024     mcld::error(mcld::diag::err_invalid_emulation) << pEmulation << "\n";
   1025 
   1026   return result;
   1027 }
   1028 
   1029 static bool ShouldColorize()
   1030 {
   1031    const char* term = getenv("TERM");
   1032    return term && (0 != strcmp(term, "dumb"));
   1033 }
   1034 
   1035 static bool ProcessLinkerOptionsFromCommand(mcld::LinkerScript& pScript,
   1036                                             mcld::LinkerConfig& pConfig)
   1037 {
   1038   // -----  Set up General Options  ----- //
   1039   // set up colorize
   1040   switch (ArgColor) {
   1041     case color::Never:
   1042       pConfig.options().setColor(false);
   1043     break;
   1044     case color::Always:
   1045       pConfig.options().setColor(true);
   1046     break;
   1047     case color::Auto:
   1048       bool color_option = ShouldColorize() &&
   1049                  llvm::sys::Process::FileDescriptorIsDisplayed(STDOUT_FILENO);
   1050       pConfig.options().setColor(color_option);
   1051     break;
   1052   }
   1053 
   1054   mcld::outs().setColor(pConfig.options().color());
   1055   mcld::errs().setColor(pConfig.options().color());
   1056 
   1057   // set up soname
   1058   pConfig.options().setSOName(ArgSOName);
   1059 
   1060   // add all rpath entries
   1061   cl::list<std::string>::iterator rp;
   1062   cl::list<std::string>::iterator rpEnd = ArgRuntimePath.end();
   1063   for (rp = ArgRuntimePath.begin(); rp != rpEnd; ++rp) {
   1064     pConfig.options().getRpathList().push_back(*rp);
   1065   }
   1066 
   1067   // --fatal-warnings
   1068   // pConfig.options().setFatalWarnings(ArgFatalWarnings);
   1069 
   1070   // -shared or -pie
   1071   if (true == ArgShared || true == ArgPIE) {
   1072     ArgFileType = mcld::CGFT_DSOFile;
   1073   }
   1074   else if (true == ArgRelocatable) {
   1075     ArgFileType = mcld::CGFT_PARTIAL;
   1076   }
   1077   else if (format::Binary == ArgOFormat) {
   1078     ArgFileType = mcld::CGFT_BINARY;
   1079   }
   1080 
   1081   // -b [input-format], --format=[input-format]
   1082   if (format::Binary == ArgFormat)
   1083     pConfig.options().setBinaryInput();
   1084 
   1085   // -V
   1086   if (ArgVersion) {
   1087     mcld::outs() << "MCLinker - "
   1088                  << mcld::LinkerConfig::version()
   1089                  << "\n";
   1090   }
   1091 
   1092   // set up sysroot
   1093   if (!ArgSysRoot.empty()) {
   1094     if (exists(ArgSysRoot) && is_directory(ArgSysRoot))
   1095       pScript.setSysroot(ArgSysRoot);
   1096   }
   1097 
   1098   // add all search directories
   1099   cl::list<std::string>::iterator sd;
   1100   cl::list<std::string>::iterator sdEnd = ArgSearchDirList.end();
   1101   for (sd=ArgSearchDirList.begin(); sd!=sdEnd; ++sd) {
   1102     if (!pScript.directories().insert(*sd)) {
   1103       // FIXME: need a warning function
   1104       errs() << "WARNING: can not open search directory `-L"
   1105              << *sd
   1106              << "'.\n";
   1107     }
   1108   }
   1109 
   1110   pConfig.options().setPIE(ArgPIE);
   1111   pConfig.options().setTrace(ArgTrace);
   1112   pConfig.options().setVerbose(ArgVerbose);
   1113   pConfig.options().setMaxErrorNum(ArgMaxErrorNum);
   1114   pConfig.options().setMaxWarnNum(ArgMaxWarnNum);
   1115   pConfig.options().setEntry(ArgEntry);
   1116   pConfig.options().setBsymbolic(ArgBsymbolic);
   1117   pConfig.options().setBgroup(ArgBgroup);
   1118   pConfig.options().setDyld(ArgDyld);
   1119   pConfig.options().setNoUndefined(ArgNoUndefined);
   1120   pConfig.options().setMulDefs(ArgAllowMulDefs);
   1121   pConfig.options().setEhFrameHdr(ArgEhFrameHdr);
   1122   pConfig.options().setNMagic(ArgNMagic);
   1123   pConfig.options().setOMagic(ArgOMagic);
   1124   pConfig.options().setStripDebug(ArgStripDebug || ArgStripAll);
   1125   pConfig.options().setExportDynamic(ArgExportDynamic);
   1126   pConfig.options().setWarnSharedTextrel(ArgWarnSharedTextrel);
   1127   pConfig.options().setDefineCommon(ArgDefineCommon);
   1128   pConfig.options().setNewDTags(ArgEnableNewDTags);
   1129   pConfig.options().setHashStyle(ArgHashStyle);
   1130   pConfig.options().setNoStdlib(ArgNoStdlib);
   1131   pConfig.options().setPrintMap(ArgPrintMap);
   1132   pConfig.options().setGPSize(ArgGPSize);
   1133 
   1134   if (ArgStripAll)
   1135     pConfig.options().setStripSymbols(mcld::GeneralOptions::StripAllSymbols);
   1136   else if (ArgDiscardAll)
   1137     pConfig.options().setStripSymbols(mcld::GeneralOptions::StripLocals);
   1138   else if (ArgDiscardLocals)
   1139     pConfig.options().setStripSymbols(mcld::GeneralOptions::StripTemporaries);
   1140   else
   1141     pConfig.options().setStripSymbols(mcld::GeneralOptions::KeepAllSymbols);
   1142 
   1143   // set up rename map, for --wrap
   1144   cl::list<std::string>::iterator wname;
   1145   cl::list<std::string>::iterator wnameEnd = ArgWrapList.end();
   1146   for (wname = ArgWrapList.begin(); wname != wnameEnd; ++wname) {
   1147     bool exist = false;
   1148 
   1149     // add wname -> __wrap_wname
   1150     mcld::StringEntry<llvm::StringRef>* to_wrap =
   1151                                      pScript.renameMap().insert(*wname, exist);
   1152 
   1153     std::string to_wrap_str = "__wrap_" + *wname;
   1154     to_wrap->setValue(to_wrap_str);
   1155 
   1156     if (exist)
   1157       mcld::warning(mcld::diag::rewrap) << *wname << to_wrap_str;
   1158 
   1159     // add __real_wname -> wname
   1160     std::string from_real_str = "__real_" + *wname;
   1161     mcld::StringEntry<llvm::StringRef>* from_real =
   1162                               pScript.renameMap().insert(from_real_str, exist);
   1163     from_real->setValue(*wname);
   1164     if (exist)
   1165       mcld::warning(mcld::diag::rewrap) << *wname << from_real_str;
   1166   } // end of for
   1167 
   1168   // set up rename map, for --portable
   1169   cl::list<std::string>::iterator pname;
   1170   cl::list<std::string>::iterator pnameEnd = ArgPortList.end();
   1171   for (pname = ArgPortList.begin(); pname != pnameEnd; ++pname) {
   1172     bool exist = false;
   1173 
   1174     // add pname -> pname_portable
   1175     mcld::StringEntry<llvm::StringRef>* to_port =
   1176                                      pScript.renameMap().insert(*pname, exist);
   1177 
   1178     std::string to_port_str = *pname + "_portable";
   1179     to_port->setValue(to_port_str);
   1180 
   1181     if (exist)
   1182       mcld::warning(mcld::diag::rewrap) << *pname << to_port_str;
   1183 
   1184     // add __real_pname -> pname
   1185     std::string from_real_str = "__real_" + *pname;
   1186     mcld::StringEntry<llvm::StringRef>* from_real =
   1187                               pScript.renameMap().insert(from_real_str, exist);
   1188 
   1189     from_real->setValue(*pname);
   1190     if (exist)
   1191       mcld::warning(mcld::diag::rewrap) << *pname << from_real_str;
   1192   } // end of for
   1193 
   1194   // add -z options
   1195   cl::list<mcld::ZOption>::iterator zOpt;
   1196   cl::list<mcld::ZOption>::iterator zOptEnd = ArgZOptionList.end();
   1197   for (zOpt = ArgZOptionList.begin(); zOpt != zOptEnd; ++zOpt) {
   1198     pConfig.options().addZOption(*zOpt);
   1199   }
   1200 
   1201   if (ArgGCSections) {
   1202     mcld::warning(mcld::diag::warn_unsupported_option) << ArgGCSections.ArgStr;
   1203   }
   1204 
   1205   // set up icf mode
   1206   switch (ArgICF) {
   1207     case icf::None:
   1208       break;
   1209     case icf::All:
   1210     case icf::Safe:
   1211     default:
   1212       mcld::warning(mcld::diag::warn_unsupported_option) << ArgICF.ArgStr;
   1213       break;
   1214   }
   1215 
   1216   if (ArgFIXCA8) {
   1217     mcld::warning(mcld::diag::warn_unsupported_option) << ArgFIXCA8.ArgStr;
   1218   }
   1219 
   1220   // add address mappings
   1221   // -Ttext
   1222   if (-1U != ArgTextSegAddr) {
   1223     bool exist = false;
   1224     mcld::StringEntry<uint64_t>* text_mapping =
   1225                                    pScript.addressMap().insert(".text", exist);
   1226     text_mapping->setValue(ArgTextSegAddr);
   1227   }
   1228   // -Tdata
   1229   if (-1U != ArgDataSegAddr) {
   1230     bool exist = false;
   1231     mcld::StringEntry<uint64_t>* data_mapping =
   1232                                    pScript.addressMap().insert(".data", exist);
   1233     data_mapping->setValue(ArgDataSegAddr);
   1234   }
   1235   // -Tbss
   1236   if (-1U != ArgBssSegAddr) {
   1237     bool exist = false;
   1238     mcld::StringEntry<uint64_t>* bss_mapping =
   1239                                     pScript.addressMap().insert(".bss", exist);
   1240     bss_mapping->setValue(ArgBssSegAddr);
   1241   }
   1242   // --section-start SECTION=ADDRESS
   1243   for (cl::list<std::string>::iterator
   1244          it = ArgAddressMapList.begin(), ie = ArgAddressMapList.end();
   1245        it != ie; ++it) {
   1246     // FIXME: Add a cl::parser
   1247     size_t pos = (*it).find_last_of('=');
   1248     llvm::StringRef script(*it);
   1249     uint64_t address = 0x0;
   1250     script.substr(pos + 1).getAsInteger(0, address);
   1251     bool exist = false;
   1252     mcld::StringEntry<uint64_t>* addr_mapping =
   1253                      pScript.addressMap().insert(script.substr(0, pos), exist);
   1254     addr_mapping->setValue(address);
   1255   }
   1256 
   1257   // --defsym symbols
   1258   for (cl::list<std::string>::iterator
   1259        it = ArgDefSymList.begin(), ie = ArgDefSymList.end();
   1260        it != ie ; ++it) {
   1261     llvm::StringRef expression(*it);
   1262     size_t pos = expression.find_last_of('=');
   1263     if (pos == expression.size() - 1) {
   1264       errs() << "defsym option: expression must not end with '='\n";
   1265       return false;
   1266     }
   1267     if (llvm::StringRef::npos == pos) {
   1268       errs() << "syntax : --defsym symbol=expression\n";
   1269       return false;
   1270     }
   1271     bool exist = false;
   1272     // FIXME: This will not work with multiple destinations such as
   1273     // --defsym abc=pqr=expression
   1274 
   1275     mcld::StringEntry<llvm::StringRef> *defsyms =
   1276                     pScript.defSymMap().insert(expression.substr(0,pos),exist);
   1277     defsyms->setValue(expression.substr(pos + 1));
   1278   }
   1279 
   1280   // set up filter/aux filter for shared object
   1281   pConfig.options().setFilter(ArgFilter);
   1282 
   1283   cl::list<std::string>::iterator aux;
   1284   cl::list<std::string>::iterator auxEnd = ArgAuxiliary.end();
   1285   for (aux = ArgAuxiliary.begin(); aux != auxEnd; ++aux)
   1286     pConfig.options().getAuxiliaryList().push_back(*aux);
   1287 
   1288   return true;
   1289 }
   1290 
   1291 int main(int argc, char* argv[])
   1292 {
   1293   sys::PrintStackTraceOnErrorSignal();
   1294 
   1295   LLVMContext &Context = getGlobalContext();
   1296   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   1297 
   1298   // Initialize targets first, so that --version shows registered targets.
   1299   InitializeAllTargets();
   1300   InitializeAllAsmPrinters();
   1301   InitializeAllAsmParsers();
   1302   InitializeAllTargetMCs();
   1303   mcld::InitializeAllTargets();
   1304   mcld::InitializeAllLinkers();
   1305   mcld::InitializeAllEmulations();
   1306   mcld::InitializeAllDiagnostics();
   1307 
   1308   cl::ParseCommandLineOptions(argc, argv, "MCLinker\n");
   1309 
   1310 #ifdef ENABLE_UNITTEST
   1311   if (UnitTest) {
   1312     return unit_test( argc, argv );
   1313   }
   1314 #endif
   1315 
   1316   // Load the module to be compiled...
   1317   std::auto_ptr<llvm::Module> M;
   1318 
   1319   // Load the module to be linked...
   1320   mcld::LinkerScript LDScript;
   1321   mcld::Module LDIRModule(LDScript);
   1322   mcld::LinkerConfig LDConfig;
   1323 
   1324   // Process the linker input from the command line
   1325   if (!ProcessLinkerOptionsFromCommand(LDScript, LDConfig)) {
   1326     errs() << argv[0] << ": failed to process linker options from command line!\n";
   1327     return 1;
   1328   }
   1329 
   1330   if (ArgBitcodeFilename.empty() &&
   1331       (mcld::CGFT_DSOFile != ArgFileType &&
   1332        mcld::CGFT_EXEFile != ArgFileType &&
   1333        mcld::CGFT_PARTIAL != ArgFileType &&
   1334        mcld::CGFT_BINARY  != ArgFileType)) {
   1335     // If the file is not given, forcefully read from stdin
   1336     if (ArgVerbose >= 0) {
   1337       errs() << "** The bitcode/llvm asm file is not given. Read from stdin.\n"
   1338              << "** Specify input bitcode/llvm asm file by\n\n"
   1339              << "          llvm-mcld -dB [the bitcode/llvm asm]\n\n";
   1340     }
   1341 
   1342     ArgBitcodeFilename.assign("-");
   1343   }
   1344 
   1345   if (!ArgBitcodeFilename.empty()) {
   1346     SMDiagnostic Err;
   1347     M.reset(ParseIRFile(ArgBitcodeFilename.native(), Err, Context));
   1348 
   1349     if (M.get() == 0) {
   1350       Err.print(argv[0], errs());
   1351       errs() << "** Failed to to the given bitcode/llvm asm file '"
   1352              << ArgBitcodeFilename.native() << "'. **\n";
   1353       return 1;
   1354     }
   1355   }
   1356   else {
   1357     // If here, output must be dynamic shared object (mcld::CGFT_DSOFile) and
   1358     // executable file (mcld::CGFT_EXEFile).
   1359     M.reset(new Module("Empty Module", Context));
   1360   }
   1361   Module &mod = *M.get();
   1362 
   1363   // If we are supposed to override the target triple, do so now.
   1364   Triple TheTriple;
   1365   if (!TargetTriple.empty()) {
   1366     // 1. Use the triple from command.
   1367     TheTriple.setTriple(TargetTriple);
   1368     mod.setTargetTriple(TargetTriple);
   1369   } else if (!mod.getTargetTriple().empty()) {
   1370     // 2. Use the triple in the input Module.
   1371     TheTriple.setTriple(mod.getTargetTriple());
   1372   } else {
   1373     std::string ProgNameTriple = ParseProgName(argv[0]);
   1374     if (!ProgNameTriple.empty()) {
   1375       // 3. Use the triple from the program name prefix.
   1376       TheTriple.setTriple(ProgNameTriple);
   1377       mod.setTargetTriple(ProgNameTriple);
   1378     } else {
   1379       // 4. Use the default target triple.
   1380       TheTriple.setTriple(mcld::sys::getDefaultTargetTriple());
   1381       if (!ArgEmulation.empty()) {
   1382         // Process target emulation.
   1383         Triple EmulationTriple = ParseEmulation(ArgEmulation);
   1384         if (EmulationTriple.getArch() != Triple::UnknownArch)
   1385           TheTriple.setArch(EmulationTriple.getArch());
   1386         if (EmulationTriple.getOS() != Triple::UnknownOS)
   1387           TheTriple.setOS(EmulationTriple.getOS());
   1388         if (EmulationTriple.getEnvironment() != Triple::UnknownEnvironment)
   1389           TheTriple.setEnvironment(EmulationTriple.getEnvironment());
   1390       }
   1391     }
   1392   }
   1393 
   1394   // Allocate target machine.  First, check whether the user has explicitly
   1395   // specified an architecture to compile for. If so we have to look it up by
   1396   // name, because it might be a backend that has no mapping to a target triple.
   1397   const mcld::Target *TheTarget = 0;
   1398   if (!MArch.empty()) {
   1399     for (mcld::TargetRegistry::iterator it = mcld::TargetRegistry::begin(),
   1400            ie = mcld::TargetRegistry::end(); it != ie; ++it) {
   1401       if (MArch == (*it)->get()->getName()) {
   1402         TheTarget = *it;
   1403         break;
   1404       }
   1405     }
   1406 
   1407     if (!TheTarget) {
   1408       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
   1409       return 1;
   1410     }
   1411 
   1412     // Adjust the triple to match (if known), otherwise stick with the
   1413     // module/host triple.
   1414     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
   1415     if (Type != Triple::UnknownArch)
   1416       TheTriple.setArch(Type);
   1417   }
   1418   else {
   1419     std::string Err;
   1420     TheTarget = mcld::TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
   1421     if (TheTarget == 0) {
   1422       errs() << "error: auto-selecting target `" << TheTriple.getTriple()
   1423              << "'\n"
   1424              << "Please use the -march option to explicitly select a target.\n"
   1425              << "Example:\n"
   1426              << "  $ " << argv[0] << " -march=arm\n";
   1427       return 1;
   1428     }
   1429   }
   1430   // Set up mcld::LinkerConfig
   1431   LDConfig.targets().setTriple(TheTriple);
   1432 
   1433   // Package up features to be passed to target/subtarget
   1434   std::string FeaturesStr;
   1435   if (MAttrs.size()) {
   1436     SubtargetFeatures Features;
   1437     for (unsigned i = 0; i != MAttrs.size(); ++i)
   1438       Features.AddFeature(MAttrs[i]);
   1439     FeaturesStr = Features.getString();
   1440   }
   1441 
   1442   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
   1443   switch (OptLevel) {
   1444   default:
   1445     errs() << argv[0] << ": invalid optimization level.\n";
   1446     return 1;
   1447   case ' ': break;
   1448   case '0': OLvl = CodeGenOpt::None; break;
   1449   case '1': OLvl = CodeGenOpt::Less; break;
   1450   case '2': OLvl = CodeGenOpt::Default; break;
   1451   case '3': OLvl = CodeGenOpt::Aggressive; break;
   1452   }
   1453 
   1454   // set -fPIC
   1455   if (ArgFPIC)
   1456     ArgRelocModel = Reloc::PIC_;
   1457 
   1458   TargetOptions Options;
   1459   Options.LessPreciseFPMADOption = EnableFPMAD;
   1460   Options.NoFramePointerElim = DisableFPElim;
   1461   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
   1462   Options.AllowFPOpFusion = FuseFPOps;
   1463   Options.UnsafeFPMath = EnableUnsafeFPMath;
   1464   Options.NoInfsFPMath = EnableNoInfsFPMath;
   1465   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
   1466   Options.HonorSignDependentRoundingFPMathOption =
   1467       EnableHonorSignDependentRoundingFPMath;
   1468   Options.UseSoftFloat = GenerateSoftFloatCalls;
   1469   if (FloatABIForCalls != FloatABI::Default)
   1470     Options.FloatABIType = FloatABIForCalls;
   1471   Options.NoZerosInBSS = DontPlaceZerosInBSS;
   1472   Options.JITExceptionHandling = EnableJITExceptionHandling;
   1473   Options.JITEmitDebugInfo = EmitJitDebugInfo;
   1474   Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
   1475   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
   1476   Options.StackAlignmentOverride = OverrideStackAlignment;
   1477   Options.RealignStack = EnableRealignStack;
   1478   Options.TrapFuncName = TrapFuncName;
   1479   Options.EnableSegmentedStacks = SegmentedStacks;
   1480 
   1481   std::auto_ptr<mcld::MCLDTargetMachine> target_machine(
   1482           TheTarget->createTargetMachine(TheTriple.getTriple(),
   1483                                          MCPU, FeaturesStr, Options,
   1484                                          ArgRelocModel, CMModel, OLvl));
   1485   assert(target_machine.get() && "Could not allocate target machine!");
   1486   mcld::MCLDTargetMachine &TheTargetMachine = *target_machine.get();
   1487 
   1488   LDConfig.targets().setTargetCPU(MCPU);
   1489   LDConfig.targets().setTargetFeatureString(FeaturesStr);
   1490 
   1491   TheTargetMachine.getTM().setMCUseLoc(false);
   1492   TheTargetMachine.getTM().setMCUseCFI(false);
   1493 
   1494   // FIXME: Move the initialization of LineInfo to mcld::Linker when we
   1495   // finish LineInfo's implementation.
   1496   OwningPtr<mcld::DiagnosticLineInfo>
   1497     diag_line_info(TheTarget->createDiagnosticLineInfo(*TheTarget,
   1498                                                        TheTriple.getTriple()));
   1499 
   1500   mcld::getDiagnosticEngine().setLineInfo(*diag_line_info.take());
   1501 
   1502   // Figure out where we are going to send the output...
   1503   OwningPtr<mcld::ToolOutputFile>
   1504   Out(GetOutputStream(TheTarget->get()->getName(),
   1505                       TheTriple.getOS(),
   1506                       ArgFileType,
   1507                       ArgBitcodeFilename,
   1508                       ArgOutputFilename));
   1509   if (!Out) {
   1510     // FIXME: show some error message pls.
   1511     return 1;
   1512   }
   1513 
   1514   // Build up all of the passes that we want to do to the module.
   1515   PassManager PM;
   1516 
   1517   // Add the data layout from the target machine, if it exists, or the module.
   1518   if (const DataLayout *DL = TheTargetMachine.getTM().getDataLayout())
   1519     PM.add(new DataLayout(*DL));
   1520    else
   1521     PM.add(new DataLayout(&mod));
   1522 
   1523   // Override default to generate verbose assembly.
   1524   TheTargetMachine.getTM().setAsmVerbosityDefault(true);
   1525 
   1526   {
   1527     // Ask the target to add backend passes as necessary.
   1528     if( TheTargetMachine.addPassesToEmitFile(PM,
   1529                                              *Out,
   1530                                              ArgFileType,
   1531                                              OLvl,
   1532                                              LDIRModule,
   1533                                              LDConfig,
   1534                                              NoVerify)) {
   1535       errs() << argv[0] << ": target does not support generation of this"
   1536              << " file type!\n";
   1537       return 1;
   1538     }
   1539 
   1540     // Before executing passes, print the final values of the LLVM options.
   1541     cl::PrintOptionValues();
   1542 
   1543     PM.run(mod);
   1544   }
   1545 
   1546   if (mcld::getDiagnosticEngine().getPrinter()->getNumErrors())
   1547     return 1;
   1548 
   1549   // Declare success.
   1550   Out->keep();
   1551   return 0;
   1552 }
   1553