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/Target/TargetMachine.h>
10#include <mcld/Support/TargetSelect.h>
11#include <mcld/Support/TargetRegistry.h>
12#include <mcld/Support/CommandLine.h>
13#include <mcld/Support/DerivedPositionDependentOptions.h>
14#include <mcld/Support/RealPath.h>
15#include <mcld/CodeGen/SectLinkerOption.h>
16
17#include <llvm/Module.h>
18#include <llvm/PassManager.h>
19#include <llvm/Pass.h>
20#include <llvm/ADT/Triple.h>
21#include <llvm/LLVMContext.h>
22#include <llvm/MC/SubtargetFeature.h>
23#include <llvm/Support/CommandLine.h>
24#include <llvm/Support/Debug.h>
25#include <llvm/Support/FormattedStream.h>
26#include <llvm/Support/Host.h>
27#include <llvm/Support/IRReader.h>
28#include <llvm/Support/ManagedStatic.h>
29#include <llvm/Support/TargetRegistry.h>
30#include <llvm/Support/TargetSelect.h>
31#include <llvm/Support/ToolOutputFile.h>
32#include <llvm/Target/TargetData.h>
33#include <llvm/Target/TargetMachine.h>
34
35using namespace llvm;
36
37#ifdef ENABLE_UNITTEST
38#include <gtest.h>
39
40static cl::opt<bool>
41UnitTest("unittest",  cl::desc("do unit test") );
42
43int unit_test( int argc, char* argv[] )
44{
45  testing::InitGoogleTest( &argc, argv );
46  return RUN_ALL_TESTS();
47}
48
49#endif
50
51
52// General options for llc.  Other pass-specific options are specified
53// within the corresponding llc passes, and target-specific options
54// and back-end code generation options are specified with the target machine.
55//
56static cl::opt<std::string>
57InputFilename("dB",
58              cl::desc("set default bitcode"),
59              cl::value_desc("bitcode"));
60
61static cl::opt<std::string>
62OutputFilename("o",
63               cl::desc("Output filename"),
64               cl::value_desc("filename"));
65
66// Determine optimization level.
67static cl::opt<char>
68OptLevel("O",
69         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70                  "(default = '-O2')"),
71         cl::Prefix,
72         cl::ZeroOrMore,
73         cl::init(' '));
74
75static cl::opt<std::string>
76TargetTriple("mtriple", cl::desc("Override target triple for module"));
77
78static cl::opt<std::string>
79MArch("march", cl::desc("Architecture to generate code for (see --version)"));
80
81static cl::opt<std::string>
82MCPU("mcpu",
83  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
84  cl::value_desc("cpu-name"),
85  cl::init(""));
86
87static cl::list<std::string>
88MAttrs("mattr",
89  cl::CommaSeparated,
90  cl::desc("Target specific attributes (-mattr=help for details)"),
91  cl::value_desc("a1,+a2,-a3,..."));
92
93static cl::opt<Reloc::Model>
94RelocModel("relocation-model",
95             cl::desc("Choose relocation model"),
96             cl::init(Reloc::Default),
97             cl::values(
98            clEnumValN(Reloc::Default, "default",
99                       "Target default relocation model"),
100            clEnumValN(Reloc::Static, "static",
101                       "Non-relocatable code"),
102            clEnumValN(Reloc::PIC_, "pic",
103                       "Fully relocatable, position independent code"),
104            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
105                       "Relocatable external references, non-relocatable code"),
106            clEnumValEnd));
107
108static cl::opt<llvm::CodeModel::Model>
109CMModel("code-model",
110        cl::desc("Choose code model"),
111        cl::init(CodeModel::Default),
112        cl::values(clEnumValN(CodeModel::Default, "default",
113                              "Target default code model"),
114                   clEnumValN(CodeModel::Small, "small",
115                              "Small code model"),
116                   clEnumValN(CodeModel::Kernel, "kernel",
117                              "Kernel code model"),
118                   clEnumValN(CodeModel::Medium, "medium",
119                              "Medium code model"),
120                   clEnumValN(CodeModel::Large, "large",
121                              "Large code model"),
122                   clEnumValEnd));
123
124cl::opt<mcld::CodeGenFileType>
125FileType("filetype", cl::init(mcld::CGFT_EXEFile),
126  cl::desc("Choose a file type (not all types are supported by all targets):"),
127  cl::values(
128       clEnumValN(mcld::CGFT_ASMFile, "asm",
129                  "Emit an assembly ('.s') file"),
130       clEnumValN(mcld::CGFT_OBJFile, "obj",
131                  "Emit a relocatable object ('.o') file"),
132       clEnumValN(mcld::CGFT_ARCFile, "arc",
133                  "Emit an archive ('.a') file"),
134       clEnumValN(mcld::CGFT_DSOFile, "dso",
135                  "Emit an dynamic shared object ('.so') file"),
136       clEnumValN(mcld::CGFT_EXEFile, "exe",
137                  "Emit a executable ('.exe') file"),
138       clEnumValN(mcld::CGFT_NULLFile, "null",
139                  "Emit nothing, for performance testing"),
140       clEnumValEnd));
141
142cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
143                       cl::desc("Do not verify input module"));
144
145static cl::opt<bool>
146EnableFPMAD("enable-fp-mad",
147  cl::desc("Enable less precise MAD instructions to be generated"),
148  cl::init(false));
149
150static cl::opt<bool>
151PrintCode("print-machineinstrs",
152  cl::desc("Print generated machine code"),
153  cl::init(false));
154
155static cl::opt<bool>
156DisableFPElim("disable-fp-elim",
157  cl::desc("Disable frame pointer elimination optimization"),
158  cl::init(false));
159
160static cl::opt<bool>
161DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
162  cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
163  cl::init(false));
164
165static cl::opt<bool>
166DisableExcessPrecision("disable-excess-fp-precision",
167  cl::desc("Disable optimizations that may increase FP precision"),
168  cl::init(false));
169
170static cl::opt<bool>
171EnableUnsafeFPMath("enable-unsafe-fp-math",
172  cl::desc("Enable optimizations that may decrease FP precision"),
173  cl::init(false));
174
175static cl::opt<bool>
176EnableNoInfsFPMath("enable-no-infs-fp-math",
177  cl::desc("Enable FP math optimizations that assume no +-Infs"),
178  cl::init(false));
179
180static cl::opt<bool>
181EnableNoNaNsFPMath("enable-no-nans-fp-math",
182  cl::desc("Enable FP math optimizations that assume no NaNs"),
183  cl::init(false));
184
185static cl::opt<bool>
186EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
187  cl::Hidden,
188  cl::desc("Force codegen to assume rounding mode can change dynamically"),
189  cl::init(false));
190
191static cl::opt<bool>
192GenerateSoftFloatCalls("soft-float",
193  cl::desc("Generate software floating point library calls"),
194  cl::init(false));
195
196static cl::opt<llvm::FloatABI::ABIType>
197FloatABIForCalls("float-abi",
198  cl::desc("Choose float ABI type"),
199  cl::init(FloatABI::Default),
200  cl::values(
201    clEnumValN(FloatABI::Default, "default",
202               "Target default float ABI type"),
203    clEnumValN(FloatABI::Soft, "soft",
204               "Soft float ABI (implied by -soft-float)"),
205    clEnumValN(FloatABI::Hard, "hard",
206               "Hard float ABI (uses FP registers)"),
207    clEnumValEnd));
208
209static cl::opt<bool>
210DontPlaceZerosInBSS("nozero-initialized-in-bss",
211  cl::desc("Don't place zero-initialized symbols into bss section"),
212  cl::init(false));
213
214static cl::opt<bool>
215EnableJITExceptionHandling("jit-enable-eh",
216  cl::desc("Emit exception handling information"),
217  cl::init(false));
218
219// In debug builds, make this default to true.
220#ifdef NDEBUG
221#define EMIT_DEBUG false
222#else
223#define EMIT_DEBUG true
224#endif
225static cl::opt<bool>
226EmitJitDebugInfo("jit-emit-debug",
227  cl::desc("Emit debug information to debugger"),
228  cl::init(EMIT_DEBUG));
229#undef EMIT_DEBUG
230
231static cl::opt<bool>
232EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
233  cl::Hidden,
234  cl::desc("Emit debug info objfiles to disk"),
235  cl::init(false));
236
237static cl::opt<bool>
238EnableGuaranteedTailCallOpt("tailcallopt",
239  cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
240  cl::init(false));
241
242static cl::opt<unsigned>
243OverrideStackAlignment("stack-alignment",
244  cl::desc("Override default stack alignment"),
245  cl::init(0));
246
247static cl::opt<bool>
248EnableRealignStack("realign-stack",
249  cl::desc("Realign stack if needed"),
250  cl::init(true));
251
252static cl::opt<bool>
253DisableSwitchTables(cl::Hidden, "disable-jump-tables",
254  cl::desc("Do not generate jump tables."),
255  cl::init(false));
256
257static cl::opt<std::string>
258TrapFuncName("trap-func", cl::Hidden,
259  cl::desc("Emit a call to trap function rather than a trap instruction"),
260  cl::init(""));
261
262static cl::opt<bool>
263SegmentedStacks("segmented-stacks",
264  cl::desc("Use segmented stacks if possible."),
265  cl::init(false));
266
267//===----------------------------------------------------------------------===//
268// Command Line Options
269// There are four kinds of command line options:
270//   1. input, (may be a file, such as -m and /tmp/XXXX.o.)
271//   2. attribute of inputs, (describing the attributes of inputs, such as
272//      --as-needed and --whole-archive. usually be positional.)
273//   3. scripting options, (represent a subset of link scripting language, such
274//      as --defsym.)
275//   4. and general options. (the rest of options)
276//===----------------------------------------------------------------------===//
277// General Options
278static cl::opt<mcld::sys::fs::Path, false, llvm::cl::parser<mcld::sys::fs::Path> >
279ArgSysRoot("sysroot",
280           cl::desc("Use directory as the location of the sysroot, overriding the configure-time default."),
281           cl::value_desc("directory"),
282           cl::ValueRequired);
283
284static cl::list<mcld::MCLDDirectory, bool, llvm::cl::parser<mcld::MCLDDirectory> >
285ArgSearchDirList("L",
286                 cl::ZeroOrMore,
287                 cl::desc("Add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts."),
288                 cl::value_desc("searchdir"),
289                 cl::Prefix);
290
291static cl::alias
292ArgSearchDirListAlias("library-path",
293                      cl::desc("alias for -L"),
294                      cl::aliasopt(ArgSearchDirList));
295
296static cl::opt<bool>
297ArgTrace("t",
298         cl::desc("Print the names of the input files as ld processes them."));
299
300static cl::alias
301ArgTraceAlias("trace",
302              cl::desc("alias for -t"),
303              cl::aliasopt(ArgTrace));
304
305static cl::opt<bool>
306ArgVerbose("V",
307          cl::desc("Display the version number for ld and list the linker emulations supported."));
308
309static cl::alias
310ArgVerboseAlias("verbose",
311                cl::desc("alias for -V"),
312                cl::aliasopt(ArgVerbose));
313
314static cl::opt<std::string>
315ArgEntry("e",
316         cl::desc("Use entry as the explicit symbol for beginning execution of your program."),
317         cl::value_desc("entry"),
318         cl::ValueRequired);
319
320static cl::alias
321ArgEntryAlias("entry",
322              cl::desc("alias for -e"),
323              cl::aliasopt(ArgEntry));
324
325static cl::opt<bool>
326ArgBsymbolic("Bsymbolic",
327             cl::desc("Bind references within the shared library."),
328             cl::init(false));
329
330static cl::opt<std::string>
331ArgSOName("soname",
332          cl::desc("Set internal name of shared library"),
333          cl::value_desc("name"));
334
335//===----------------------------------------------------------------------===//
336// Inputs
337static cl::list<mcld::sys::fs::Path>
338ArgInputObjectFiles(cl::Positional,
339                    cl::desc("[input object files]"),
340                    cl::ZeroOrMore);
341
342static cl::list<std::string>
343ArgNameSpecList("l",
344            cl::ZeroOrMore,
345            cl::desc("Add the archive or object file specified by namespec to the list of files to link."),
346            cl::value_desc("namespec"),
347            cl::Prefix);
348
349static cl::alias
350ArgNameSpecListAlias("library",
351                 cl::desc("alias for -l"),
352                 cl::aliasopt(ArgNameSpecList));
353
354static cl::list<bool>
355ArgStartGroupList("start-group",
356                  cl::ValueDisallowed,
357                  cl::desc("start to record a group of archives"));
358
359static cl::alias
360ArgStartGroupListAlias("(",
361                       cl::desc("alias for --start-group"),
362                       cl::aliasopt(ArgStartGroupList));
363
364static cl::list<bool>
365ArgEndGroupList("end-group",
366                cl::ValueDisallowed,
367                cl::desc("stop recording a group of archives"));
368
369static cl::alias
370ArgEndGroupListAlias(")",
371                     cl::desc("alias for --end-group"),
372                     cl::aliasopt(ArgEndGroupList));
373
374//===----------------------------------------------------------------------===//
375// Attributes of Inputs
376static cl::list<bool>
377ArgWholeArchiveList("whole-archive",
378                    cl::ValueDisallowed,
379                    cl::desc("For each archive mentioned on the command line after the --whole-archive option, include all object files in the archive."));
380
381static cl::list<bool>
382ArgNoWholeArchiveList("no-whole-archive",
383                    cl::ValueDisallowed,
384                    cl::desc("Turn off the effect of the --whole-archive option for subsequent archive files."));
385
386static cl::list<bool>
387ArgAsNeededList("as-needed",
388                cl::ValueDisallowed,
389                cl::desc("This option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option."));
390
391static cl::list<bool>
392ArgNoAsNeededList("no-as-needed",
393                cl::ValueDisallowed,
394                cl::desc("Turn off the effect of the --as-needed option for subsequent dynamic libraries"));
395
396static cl::list<bool>
397ArgAddNeededList("add-needed",
398                cl::ValueDisallowed,
399                cl::desc("--add-needed causes DT_NEEDED tags are always emitted for those libraries from DT_NEEDED tags. This is the default behavior."));
400
401static cl::list<bool>
402ArgNoAddNeededList("no-add-needed",
403                cl::ValueDisallowed,
404                cl::desc("--no-add-needed causes DT_NEEDED tags will never be emitted for those libraries from DT_NEEDED tags"));
405
406static cl::list<bool>
407ArgBDynamicList("Bdynamic",
408                cl::ValueDisallowed,
409                cl::desc("Link against dynamic library"));
410
411static cl::alias
412ArgBDynamicListAlias1("dy",
413                     cl::desc("alias for --Bdynamic"),
414                     cl::aliasopt(ArgBDynamicList));
415
416static cl::alias
417ArgBDynamicListAlias2("call_shared",
418                     cl::desc("alias for --Bdynamic"),
419                     cl::aliasopt(ArgBDynamicList));
420
421static cl::list<bool>
422ArgBStaticList("Bstatic",
423                cl::ValueDisallowed,
424                cl::desc("Link against static library"));
425
426static cl::alias
427ArgBStaticListAlias1("dn",
428                     cl::desc("alias for --Bstatic"),
429                     cl::aliasopt(ArgBStaticList));
430
431static cl::alias
432ArgBStaticListAlias2("static",
433                     cl::desc("alias for --Bstatic"),
434                     cl::aliasopt(ArgBStaticList));
435
436static cl::alias
437ArgBStaticListAlias3("non_shared",
438                     cl::desc("alias for --Bstatic"),
439                     cl::aliasopt(ArgBStaticList));
440
441//===----------------------------------------------------------------------===//
442// Scripting Options
443
444
445//===----------------------------------------------------------------------===//
446/// non-member functions
447
448// GetFileNameRoot - Helper function to get the basename of a filename.
449static inline void
450GetFileNameRoot(const std::string &pInputFilename, std::string& pFileNameRoot)
451{
452  std::string outputFilename;
453  /* *** */
454  const std::string& IFN = pInputFilename;
455  int Len = IFN.length();
456  if ((Len > 2) &&
457      IFN[Len-3] == '.' &&
458      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
459       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l')))
460    pFileNameRoot = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
461  else
462    pFileNameRoot = std::string(IFN);
463}
464
465static tool_output_file *GetOutputStream(const char* pTargetName,
466                          Triple::OSType pOSType,
467                          mcld::CodeGenFileType pFileType,
468                          const std::string& pInputFilename,
469                          std::string& pOutputFilename)
470{
471  // If we don't yet have an output filename, make one.
472  if (pOutputFilename.empty()) {
473    if (pInputFilename == "-")
474      pOutputFilename = "-";
475    else {
476      GetFileNameRoot(pInputFilename, pOutputFilename);
477
478      switch (pFileType) {
479      case mcld::CGFT_ASMFile:
480        if (pTargetName[0] == 'c') {
481          if (pTargetName[1] == 0)
482            pOutputFilename += ".cbe.c";
483          else if (pTargetName[1] == 'p' && pTargetName[2] == 'p')
484            pOutputFilename += ".cpp";
485          else
486            pOutputFilename += ".s";
487        }
488        else
489          pOutputFilename += ".s";
490        break;
491      case mcld::CGFT_OBJFile:
492        if (pOSType == Triple::Win32)
493          pOutputFilename += ".obj";
494        else
495          pOutputFilename += ".o";
496        break;
497      case mcld::CGFT_DSOFile:
498        if (pOSType == Triple::Win32)
499         pOutputFilename += ".dll";
500        else
501         pOutputFilename += ".so";
502        break;
503      case mcld::CGFT_ARCFile:
504         pOutputFilename += ".a";
505        break;
506      case mcld::CGFT_EXEFile:
507      case mcld::CGFT_NULLFile:
508        // do nothing
509        break;
510      default:
511        assert(0 && "Unknown file type");
512      }
513    }
514  }
515
516  // Decide if we need "binary" output.
517  bool Binary = false;
518  switch (pFileType) {
519  default: assert(0 && "Unknown file type");
520  case mcld::CGFT_ASMFile:
521    break;
522  case mcld::CGFT_ARCFile:
523  case mcld::CGFT_OBJFile:
524  case mcld::CGFT_DSOFile:
525  case mcld::CGFT_EXEFile:
526  case mcld::CGFT_NULLFile:
527    Binary = true;
528    break;
529  }
530
531  // Open the file.
532  std::string error;
533  unsigned OpenFlags = 0;
534  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
535  tool_output_file *FDOut = new tool_output_file(pOutputFilename.c_str(), error,
536                                                 OpenFlags);
537  if (!error.empty()) {
538    errs() << error << '\n';
539    delete FDOut;
540    return 0;
541  }
542
543  return FDOut;
544}
545
546static bool ProcessLinkerInputsFromCommand(mcld::SectLinkerOption &pOption) {
547  // -----  Set up General Options  ----- //
548  // set up soname
549  pOption.info().output().setSOName(ArgSOName);
550
551  // set up sysroot
552  if (!ArgSysRoot.empty()) {
553    if (exists(ArgSysRoot) && is_directory(ArgSysRoot))
554      pOption.info().options().setSysroot(ArgSysRoot);
555  }
556
557  // add all search directories
558  cl::list<mcld::MCLDDirectory>::iterator sd;
559  cl::list<mcld::MCLDDirectory>::iterator sdEnd = ArgSearchDirList.end();
560  for (sd=ArgSearchDirList.begin(); sd!=sdEnd; ++sd) {
561    if (sd->isInSysroot())
562      sd->setSysroot(pOption.info().options().sysroot());
563    if (exists(sd->path()) && is_directory(sd->path())) {
564      pOption.info().options().directories().add(*sd);
565    }
566    else {
567      // FIXME: need a warning function
568      errs() << "WARNING: can not open search directory `-L"
569             << sd->name()
570             << "'.\n";
571    }
572  }
573
574  pOption.info().options().setTrace(ArgTrace);
575  pOption.info().options().setVerbose(ArgVerbose);
576  pOption.info().options().setEntry(ArgEntry);
577  pOption.info().options().setBsymbolic(ArgBsymbolic);
578
579  // -----  Set up Inputs  ----- //
580  // add all start-group
581  cl::list<bool>::iterator sg;
582  cl::list<bool>::iterator sgEnd = ArgStartGroupList.end();
583  for (sg=ArgStartGroupList.begin(); sg!=sgEnd; ++sg) {
584    // calculate position
585    pOption.appendOption(new mcld::StartGroupOption(
586                                    ArgStartGroupList.getPosition(sg-ArgStartGroupList.begin())));
587  }
588
589  // add all end-group
590  cl::list<bool>::iterator eg;
591  cl::list<bool>::iterator egEnd = ArgEndGroupList.end();
592  for (eg=ArgEndGroupList.begin(); eg!=egEnd; ++eg) {
593    // calculate position
594    pOption.appendOption(new mcld::EndGroupOption(
595                                    ArgEndGroupList.getPosition(eg-ArgEndGroupList.begin())));
596  }
597
598  // add all namespecs
599  cl::list<std::string>::iterator ns;
600  cl::list<std::string>::iterator nsEnd = ArgNameSpecList.end();
601  for (ns=ArgNameSpecList.begin(); ns!=nsEnd; ++ns) {
602    // calculate position
603    pOption.appendOption(new mcld::NamespecOption(
604                                    ArgNameSpecList.getPosition(ns-ArgNameSpecList.begin()),
605                                    *ns));
606  }
607
608  // add all object files
609  cl::list<mcld::sys::fs::Path>::iterator obj;
610  cl::list<mcld::sys::fs::Path>::iterator objEnd = ArgInputObjectFiles.end();
611  for (obj=ArgInputObjectFiles.begin(); obj!=objEnd; ++obj) {
612    // calculate position
613    pOption.appendOption(new mcld::InputFileOption(
614                                    ArgInputObjectFiles.getPosition(obj-ArgInputObjectFiles.begin()),
615                                    *obj));
616  }
617
618  // -----  Set up Attributes of Inputs  ----- //
619  // --whole-archive
620  cl::list<bool>::iterator attr = ArgWholeArchiveList.begin();
621  cl::list<bool>::iterator attrEnd = ArgWholeArchiveList.end();
622  for (; attr!=attrEnd; ++attr) {
623    pOption.appendOption(new mcld::WholeArchiveOption(
624                                    ArgWholeArchiveList.getPosition(attr-ArgWholeArchiveList.begin())));
625  }
626
627  // --no-whole-archive
628  attr = ArgNoWholeArchiveList.begin();
629  attrEnd = ArgNoWholeArchiveList.end();
630  for (; attr!=attrEnd; ++attr) {
631    pOption.appendOption(new mcld::NoWholeArchiveOption(
632                                    ArgNoWholeArchiveList.getPosition(attr-ArgNoWholeArchiveList.begin())));
633  }
634
635  // --as-needed
636  attr = ArgAsNeededList.begin();
637  attrEnd = ArgAsNeededList.end();
638  while(attr != attrEnd) {
639    pOption.appendOption(new mcld::AsNeededOption(
640                                    ArgAsNeededList.getPosition(attr-ArgAsNeededList.begin())));
641    ++attr;
642  }
643
644  // --no-as-needed
645  attr = ArgNoAsNeededList.begin();
646  attrEnd = ArgNoAsNeededList.end();
647  while(attr != attrEnd) {
648    pOption.appendOption(new mcld::NoAsNeededOption(
649                                    ArgNoAsNeededList.getPosition(attr-ArgNoAsNeededList.begin())));
650    ++attr;
651  }
652
653  // --add-needed
654  attr = ArgAddNeededList.begin();
655  attrEnd = ArgAddNeededList.end();
656  while(attr != attrEnd) {
657    pOption.appendOption(new mcld::AddNeededOption(
658                                    ArgAddNeededList.getPosition(attr-ArgAddNeededList.begin())));
659    ++attr;
660  }
661
662  // --no-add-needed
663  attr = ArgNoAddNeededList.begin();
664  attrEnd = ArgNoAddNeededList.end();
665  while(attr != attrEnd) {
666    pOption.appendOption(new mcld::NoAddNeededOption(
667                                    ArgNoAddNeededList.getPosition(attr-ArgNoAddNeededList.begin())));
668    ++attr;
669  }
670
671  // -Bdynamic
672  attr = ArgBDynamicList.begin();
673  attrEnd = ArgBDynamicList.end();
674  while(attr != attrEnd) {
675    pOption.appendOption(new mcld::BDynamicOption(
676                                    ArgBDynamicList.getPosition(attr-ArgBDynamicList.begin())));
677  }
678
679  // -Bstatic
680  attr = ArgBStaticList.begin();
681  attrEnd = ArgBStaticList.end();
682  while(attr != attrEnd) {
683    pOption.appendOption(new mcld::BStaticOption(
684                                    ArgBStaticList.getPosition(attr-ArgBStaticList.begin())));
685    ++attr;
686  }
687
688  // -----  Set up Scripting Options  ----- //
689
690  return false;
691}
692
693int main( int argc, char* argv[] )
694{
695
696  LLVMContext &Context = getGlobalContext();
697  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
698  // Initialize targets first, so that --version shows registered targets.
699  InitializeAllTargets();
700  InitializeAllAsmPrinters();
701  InitializeAllAsmParsers();
702  InitializeAllTargetMCs();
703  mcld::InitializeAllTargets();
704  mcld::InitializeAllLinkers();
705  cl::ParseCommandLineOptions(argc, argv, "llvm MCLinker\n");
706
707#ifdef ENABLE_UNITTEST
708  if (UnitTest) {
709    return unit_test( argc, argv );
710  }
711#endif
712
713  // Load the module to be compiled...
714  std::auto_ptr<Module> M;
715
716  if (InputFilename.empty() && (FileType != mcld::CGFT_DSOFile)) {
717    // Read from stdin
718    InputFilename = "-";
719  }
720
721  if (!InputFilename.empty()) {
722    SMDiagnostic Err;
723    M.reset(ParseIRFile(InputFilename, Err, Context));
724
725    if (M.get() == 0) {
726      Err.print(argv[0], errs());
727      errs() << "** Failed to to the given bitcode/llvm asm file '"
728             << InputFilename << "'. **\n";
729      return 1;
730    }
731  } else {
732    // If here, output must be dynamic shared object (mcld::CGFT_DSOFile).
733
734    // Create an empty Module
735    M.reset(new Module("Empty Module", Context));
736  }
737  Module &mod = *M.get();
738
739  // If we are supposed to override the target triple, do so now.
740  Triple TheTriple;
741  if (!TargetTriple.empty()) {
742    TheTriple.setTriple(TargetTriple);
743    mod.setTargetTriple(TargetTriple);
744  }
745
746  // User doesn't specify the triple from command.
747  if (TheTriple.getTriple().empty()) {
748    // Try to get one from the input Module.
749    const std::string &TripleStr = mod.getTargetTriple();
750
751    if (TripleStr.empty())
752      TheTriple.setTriple(sys::getDefaultTargetTriple());
753    else
754      TheTriple.setTriple(TripleStr);
755  }
756
757  // Allocate target machine.  First, check whether the user has explicitly
758  // specified an architecture to compile for. If so we have to look it up by
759  // name, because it might be a backend that has no mapping to a target triple.
760  const mcld::Target *TheTarget = 0;
761  if (!MArch.empty()) {
762    for (mcld::TargetRegistry::iterator it = mcld::TargetRegistry::begin(),
763           ie = mcld::TargetRegistry::end(); it != ie; ++it) {
764      if (MArch == (*it)->get()->getName()) {
765        TheTarget = *it;
766        break;
767      }
768    }
769
770    if (!TheTarget) {
771      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
772      return 1;
773    }
774
775    // Adjust the triple to match (if known), otherwise stick with the
776    // module/host triple.
777    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
778    if (Type != Triple::UnknownArch)
779      TheTriple.setArch(Type);
780  }
781  else {
782    std::string Err;
783    TheTarget = mcld::TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
784    if (TheTarget == 0) {
785      errs() << argv[0] << ": error auto-selecting target for module '"
786             << Err << "'.  Please use the -march option to explicitly "
787             << "pick a target.\n";
788      return 1;
789    }
790  }
791
792  // Package up features to be passed to target/subtarget
793  std::string FeaturesStr;
794  if (MAttrs.size()) {
795    SubtargetFeatures Features;
796    for (unsigned i = 0; i != MAttrs.size(); ++i)
797      Features.AddFeature(MAttrs[i]);
798    FeaturesStr = Features.getString();
799  }
800
801  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
802  switch (OptLevel) {
803  default:
804    errs() << argv[0] << ": invalid optimization level.\n";
805    return 1;
806  case ' ': break;
807  case '0': OLvl = CodeGenOpt::None; break;
808  case '1': OLvl = CodeGenOpt::Less; break;
809  case '2': OLvl = CodeGenOpt::Default; break;
810  case '3': OLvl = CodeGenOpt::Aggressive; break;
811  }
812
813  TargetOptions Options;
814  Options.LessPreciseFPMADOption = EnableFPMAD;
815  Options.PrintMachineCode = PrintCode;
816  Options.NoFramePointerElim = DisableFPElim;
817  Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
818  Options.NoExcessFPPrecision = DisableExcessPrecision;
819  Options.UnsafeFPMath = EnableUnsafeFPMath;
820  Options.NoInfsFPMath = EnableNoInfsFPMath;
821  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
822  Options.HonorSignDependentRoundingFPMathOption =
823      EnableHonorSignDependentRoundingFPMath;
824  Options.UseSoftFloat = GenerateSoftFloatCalls;
825  if (FloatABIForCalls != FloatABI::Default)
826    Options.FloatABIType = FloatABIForCalls;
827  Options.NoZerosInBSS = DontPlaceZerosInBSS;
828  Options.JITExceptionHandling = EnableJITExceptionHandling;
829  Options.JITEmitDebugInfo = EmitJitDebugInfo;
830  Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
831  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
832  Options.StackAlignmentOverride = OverrideStackAlignment;
833  Options.RealignStack = EnableRealignStack;
834  Options.DisableJumpTables = DisableSwitchTables;
835  Options.TrapFuncName = TrapFuncName;
836  Options.EnableSegmentedStacks = SegmentedStacks;
837
838  std::auto_ptr<mcld::LLVMTargetMachine> target_machine(
839          TheTarget->createTargetMachine(TheTriple.getTriple(),
840                                         MCPU, FeaturesStr, Options,
841                                         RelocModel, CMModel, OLvl));
842  assert(target_machine.get() && "Could not allocate target machine!");
843  mcld::LLVMTargetMachine &TheTargetMachine = *target_machine.get();
844
845  TheTargetMachine.getTM().setMCUseLoc(false);
846  TheTargetMachine.getTM().setMCUseCFI(false);
847
848  // Figure out where we are going to send the output...
849  OwningPtr<tool_output_file>
850  Out(GetOutputStream(TheTarget->get()->getName(),
851                      TheTriple.getOS(),
852                      FileType,
853                      InputFilename,
854                      OutputFilename));
855  if (!Out) return 1;
856
857  // Build up all of the passes that we want to do to the module.
858  PassManager PM;
859
860  // Add the target data from the target machine, if it exists, or the module.
861  if (const TargetData *TD = TheTargetMachine.getTM().getTargetData())
862    PM.add(new TargetData(*TD));
863  else
864    PM.add(new TargetData(&mod));
865
866  // Override default to generate verbose assembly.
867  TheTargetMachine.getTM().setAsmVerbosityDefault(true);
868
869  // Process the linker input from the command line
870  mcld::SectLinkerOption *LinkerOpt =
871      new mcld::SectLinkerOption(TheTargetMachine.getLDInfo());
872
873  if (ProcessLinkerInputsFromCommand(*LinkerOpt)) {
874    errs() << argv[0] << ": failed to process inputs from command line!\n";
875    return 1;
876  }
877
878  {
879    formatted_raw_ostream FOS(Out->os());
880
881    // Ask the target to add backend passes as necessary.
882    if( TheTargetMachine.addPassesToEmitFile(PM,
883                                             FOS,
884                                             OutputFilename,
885                                             FileType,
886                                             OLvl,
887                                             LinkerOpt,
888                                             NoVerify)) {
889      errs() << argv[0] << ": target does not support generation of this"
890             << " file type!\n";
891      return 1;
892    }
893
894    // Before executing passes, print the final values of the LLVM options.
895    cl::PrintOptionValues();
896
897    PM.run(mod);
898  }
899
900  // Declare success.
901  Out->keep();
902
903  // clean up
904  delete LinkerOpt;
905
906  return 0;
907}
908
909