From eae5a13078037e6b6591fd4f414452a7075cecf7 Mon Sep 17 00:00:00 2001 From: Eric Christopher Date: Tue, 20 Sep 2011 00:34:27 +0000 Subject: [PATCH] Remove more of llvmc and dependencies. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@140121 91177308-0d34-0410-b5e6-96231b3b80d8 --- docs/CommandGuide/index.html | 3 - docs/CommandGuide/llvmc.pod | 190 - docs/CompilerDriver.html | 687 ---- docs/CompilerDriverTutorial.html | 125 - docs/FAQ.html | 5 +- docs/index.html | 8 - include/llvm/CompilerDriver/Action.h | 54 - include/llvm/CompilerDriver/AutoGenerated.h | 40 - include/llvm/CompilerDriver/BuiltinOptions.h | 39 - include/llvm/CompilerDriver/Common.td | 127 - .../llvm/CompilerDriver/CompilationGraph.h | 330 -- include/llvm/CompilerDriver/Error.h | 29 - include/llvm/CompilerDriver/Main.h | 21 - include/llvm/CompilerDriver/Main.inc | 23 - include/llvm/CompilerDriver/Tool.h | 100 - lib/CompilerDriver/Action.cpp | 134 - lib/CompilerDriver/BuiltinOptions.cpp | 61 - lib/CompilerDriver/CMakeLists.txt | 12 - lib/CompilerDriver/CompilationGraph.cpp | 655 ---- lib/CompilerDriver/Main.cpp | 146 - lib/CompilerDriver/Makefile | 20 - lib/CompilerDriver/Tool.cpp | 95 - lib/Makefile | 2 +- utils/TableGen/CMakeLists.txt | 1 - utils/TableGen/LLVMCConfigurationEmitter.cpp | 3134 ----------------- utils/TableGen/LLVMCConfigurationEmitter.h | 34 - utils/TableGen/TableGen.cpp | 7 - 27 files changed, 2 insertions(+), 6080 deletions(-) delete mode 100644 docs/CommandGuide/llvmc.pod delete mode 100644 docs/CompilerDriver.html delete mode 100644 docs/CompilerDriverTutorial.html delete mode 100644 include/llvm/CompilerDriver/Action.h delete mode 100644 include/llvm/CompilerDriver/AutoGenerated.h delete mode 100644 include/llvm/CompilerDriver/BuiltinOptions.h delete mode 100644 include/llvm/CompilerDriver/Common.td delete mode 100644 include/llvm/CompilerDriver/CompilationGraph.h delete mode 100644 include/llvm/CompilerDriver/Error.h delete mode 100644 include/llvm/CompilerDriver/Main.h delete mode 100644 include/llvm/CompilerDriver/Main.inc delete mode 100644 include/llvm/CompilerDriver/Tool.h delete mode 100644 lib/CompilerDriver/Action.cpp delete mode 100644 lib/CompilerDriver/BuiltinOptions.cpp delete mode 100644 lib/CompilerDriver/CMakeLists.txt delete mode 100644 lib/CompilerDriver/CompilationGraph.cpp delete mode 100644 lib/CompilerDriver/Main.cpp delete mode 100644 lib/CompilerDriver/Makefile delete mode 100644 lib/CompilerDriver/Tool.cpp delete mode 100644 utils/TableGen/LLVMCConfigurationEmitter.cpp delete mode 100644 utils/TableGen/LLVMCConfigurationEmitter.h diff --git a/docs/CommandGuide/index.html b/docs/CommandGuide/index.html index b839d3cb32c..6f217db4d0e 100644 --- a/docs/CommandGuide/index.html +++ b/docs/CommandGuide/index.html @@ -69,9 +69,6 @@ options) arguments to the tool you are interested in.

  • llvm-config - print out LLVM compilation options, libraries, etc. as configured
  • -
  • llvmc - - a generic customizable compiler driver
  • -
  • llvm-diff - structurally compare two modules
  • diff --git a/docs/CommandGuide/llvmc.pod b/docs/CommandGuide/llvmc.pod deleted file mode 100644 index 95a9e5ef361..00000000000 --- a/docs/CommandGuide/llvmc.pod +++ /dev/null @@ -1,190 +0,0 @@ -=pod - -=head1 NAME - -llvmc - The LLVM Compiler Driver (WIP) - -=head1 SYNOPSIS - -B [I] I - -=head1 DESCRIPTION - -B is a configurable driver for invoking other LLVM (and non-LLVM) tools -in order to compile, optimize and link software for multiple languages. For -those familiar with FSF's B tool, it is very similar. Please note that -B is considered an experimental tool. - -=head1 OPTIONS - -=head2 Built-in Options - -LLVMC has some built-in options that can't be overridden in the -configuration libraries. - -=over - -=item B<-o> I - -Output file name. - -=item B<-x> I - -Specify the language of the following input files until the next B<-x> -option. - -=item B<-load> I - -Load the specified plugin DLL. Example: -S<-load $LLVM_DIR/Release/lib/LLVMCSimple.so>. - -=item B<-v> or B<--verbose> - -Enable verbose mode, i.e. print out all executed commands. - -=item B<--check-graph> - -Check the compilation for common errors like mismatched output/input language -names, multiple default edges and cycles. Because of plugins, these checks can't -be performed at compile-time. Exit with code zero if no errors were found, and -return the number of found errors otherwise. Hidden option, useful for debugging -LLVMC plugins. - -=item B<--view-graph> - -Show a graphical representation of the compilation graph and exit. Requires that -you have I and I programs installed. Hidden option, useful for -debugging LLVMC plugins. - -=item B<--write-graph> - -Write a I file in the current directory with the -compilation graph description in Graphviz format (identical to the file used by -the B<--view-graph> option). The B<-o> option can be used to set the output file -name. Hidden option, useful for debugging LLVMC plugins. - -=item B<--save-temps> - -Write temporary files to the current directory and do not delete them on -exit. This option can also take an argument: the I<--save-temps=obj> switch will -write files into the directory specified with the I<-o> option. The -I<--save-temps=cwd> and I<--save-temps> switches are both synonyms for the -default behaviour. - -=item B<--temp-dir> I - -Store temporary files in the given directory. This directory is deleted on exit -unless I<--save-temps> is specified. If I<--save-temps=obj> is also specified, -I<--temp-dir> is given the precedence. - -=item B<-help> - -Print a summary of command-line options and exit. - -=item B<-help-hidden> - -Print a summary of command-line options and exit. Print help even for -options intended for developers. - -=item B<--version> - -Print version information and exit. - -=item B<@>I - -Read command-line options from I. The options read are inserted -in place of the original @I option. If I does not exist, or -cannot be read, then the option will be treated literally, and not -removed. - -Options in I are separated by whitespace. A whitespace character -may be included in an option by surrounding the entire option in -either single or double quotes. Any character (including a backslash) -may be included by prefixing the character to be included with a -backslash. The file may itself contain additional @I options; -any such options will be processed recursively. - - -=back - - -=head2 Control Options - -By default, LLVMC is built with some standard configuration libraries -that define the following options: - -=over - -=item B<-clang> - -Use Clang instead of llvm-gcc. - -=item B<-opt> - -Enable optimization passes with B. To pass options to the B program -use the B<-Wo,> option. - -=item B<-I> I - -Add a directory to the header file search path. - -=item B<-L> I - -Add I to the library search path. - -=item B<-F> I - -Add I to the framework search path. - -=item B<-l>I - -Link in the library libI.[bc | a | so]. This library should -be a bitcode library. - -=item B<-framework> I - -Link in the library libI.[bc | a | so]. This library should -be a bitcode library. - -=item B<-emit-llvm> - -Output LLVM bitcode (with B<-c>) or assembly (with B<-S>) instead of native -object (or assembly). If B<-emit-llvm> is given without either B<-c> or B<-S> -it has no effect. - -=item B<-Wa> - -Pass options to assembler. - -=item B<-Wl> - -Pass options to linker. - -=item B<-Wo> - -Pass options to opt. - -=item B<-Wllc> - -Pass options to llc (code generator). - -=back - -=head1 EXIT STATUS - -If B succeeds, it will exit with code 0. Otherwise, if an -error occurs, it will exit with a non-zero value. If one of the -compilation tools returns a non-zero status, pending actions will be -discarded and B will return the same result code as the failing -compilation tool. - -=head1 SEE ALSO - -L, L, L, -L, L, L - -=head1 AUTHORS - -Maintained by the LLVM Team (L). - -=cut diff --git a/docs/CompilerDriver.html b/docs/CompilerDriver.html deleted file mode 100644 index 0f5d3592a25..00000000000 --- a/docs/CompilerDriver.html +++ /dev/null @@ -1,687 +0,0 @@ - - - - - - -Customizing LLVMC: Reference Manual - - - -
    -

    Customizing LLVMC: Reference Manual

    - - - -
    -

    Written by Mikhail Glushenkov

    -
    -

    Introduction

    -

    LLVMC is a generic compiler driver, designed to be customizable and -extensible. It plays the same role for LLVM as the gcc program does for -GCC - LLVMC's job is essentially to transform a set of input files into a set of -targets depending on configuration rules and user options. What makes LLVMC -different is that these transformation rules are completely customizable - in -fact, LLVMC knows nothing about the specifics of transformation (even the -command-line options are mostly not hard-coded) and regards the transformation -structure as an abstract graph. The structure of this graph is described in -high-level TableGen code, from which an efficient C++ representation is -automatically derived. This makes it possible to adapt LLVMC for other -purposes - for example, as a build tool for game resources.

    -

    Because LLVMC employs TableGen as its configuration language, you -need to be familiar with it to customize LLVMC.

    -
    -
    -

    Compiling with llvmc

    -

    LLVMC tries hard to be as compatible with gcc as possible, -although there are some small differences. Most of the time, however, -you shouldn't be able to notice them:

    -
    -$ # This works as expected:
    -$ llvmc -O3 -Wall hello.cpp
    -$ ./a.out
    -hello
    -
    -

    One nice feature of LLVMC is that one doesn't have to distinguish between -different compilers for different languages (think g++ vs. gcc) - the -right toolchain is chosen automatically based on input language names (which -are, in turn, determined from file extensions). If you want to force files -ending with ".c" to compile as C++, use the -x option, just like you would -do it with gcc:

    -
    -$ # hello.c is really a C++ file
    -$ llvmc -x c++ hello.c
    -$ ./a.out
    -hello
    -
    -

    On the other hand, when using LLVMC as a linker to combine several C++ -object files you should provide the --linker option since it's -impossible for LLVMC to choose the right linker in that case:

    -
    -$ llvmc -c hello.cpp
    -$ llvmc hello.o
    -[A lot of link-time errors skipped]
    -$ llvmc --linker=c++ hello.o
    -$ ./a.out
    -hello
    -
    -

    By default, LLVMC uses llvm-gcc to compile the source code. It is also -possible to choose the clang compiler with the -clang option.

    -
    -
    -

    Predefined options

    -

    LLVMC has some built-in options that can't be overridden in the TableGen code:

    -
      -
    • -o FILE - Output file name.
    • -
    • -x LANGUAGE - Specify the language of the following input files -until the next -x option.
    • -
    • -v - Enable verbose mode, i.e. print out all executed commands.
    • -
    • --save-temps - Write temporary files to the current directory and do not -delete them on exit. This option can also take an argument: the ---save-temps=obj switch will write files into the directory specified with -the -o option. The --save-temps=cwd and --save-temps switches are -both synonyms for the default behaviour.
    • -
    • --temp-dir DIRECTORY - Store temporary files in the given directory. This -directory is deleted on exit unless --save-temps is specified. If ---save-temps=obj is also specified, --temp-dir is given the -precedence.
    • -
    • --check-graph - Check the compilation for common errors like mismatched -output/input language names, multiple default edges and cycles. Exit with code -zero if no errors were found, and return the number of found errors -otherwise. Hidden option, useful for debugging.
    • -
    • --view-graph - Show a graphical representation of the compilation graph -and exit. Requires that you have dot and gv programs installed. Hidden -option, useful for debugging.
    • -
    • --write-graph - Write a compilation-graph.dot file in the current -directory with the compilation graph description in Graphviz format (identical -to the file used by the --view-graph option). The -o option can be -used to set the output file name. Hidden option, useful for debugging.
    • -
    • --help, --help-hidden, --version - These options have -their standard meaning.
    • -
    -
    -
    -

    Compiling LLVMC-based drivers

    -

    It's easiest to start working on your own LLVMC driver by copying the skeleton -project which lives under $LLVMC_DIR/examples/Skeleton:

    -
    -$ cd $LLVMC_DIR/examples
    -$ cp -r Skeleton MyDriver
    -$ cd MyDriver
    -$ ls
    -AutoGenerated.td  Hooks.cpp  Main.cpp  Makefile
    -
    -

    As you can see, our basic driver consists of only three files (not counting the -build script). AutoGenerated.td contains TableGen description of the -compilation graph; its format is documented in the following -sections. Hooks.cpp is an empty file that should be used for hook -definitions (see below). Main.cpp is just a helper used to compile the -auto-generated C++ code produced from TableGen source.

    -

    The first thing that you should do is to change the LLVMC_BASED_DRIVER -variable in the Makefile:

    -
    -LLVMC_BASED_DRIVER=MyDriver
    -
    -

    It can also be a good idea to put your TableGen code into a file with a less -generic name:

    -
    -$ touch MyDriver.td
    -$ vim AutoGenerated.td
    -[...]
    -include "MyDriver.td"
    -
    -

    If you have more than one TableGen source file, they all should be included from -AutoGenerated.td, since this file is used by the build system to generate -C++ code.

    -

    To build your driver, just cd to its source directory and run make. The -resulting executable will be put into $LLVM_OBJ_DIR/$(BuildMode)/bin.

    -

    If you're compiling LLVM with different source and object directories, then you -must perform the following additional steps before running make:

    -
    -# LLVMC_SRC_DIR = $LLVM_SRC_DIR/tools/llvmc/
    -# LLVMC_OBJ_DIR = $LLVM_OBJ_DIR/tools/llvmc/
    -$ mkdir $LLVMC_OBJ_DIR/examples/MyDriver/
    -$ cp $LLVMC_SRC_DIR/examples/MyDriver/Makefile \
    -  $LLVMC_OBJ_DIR/examples/MyDriver/
    -$ cd $LLVMC_OBJ_DIR/examples/MyDriver
    -$ make
    -
    -
    -
    -

    Customizing LLVMC: the compilation graph

    -

    Each TableGen configuration file should include the common definitions:

    -
    -include "llvm/CompilerDriver/Common.td"
    -
    -

    Internally, LLVMC stores information about possible source transformations in -form of a graph. Nodes in this graph represent tools, and edges between two -nodes represent a transformation path. A special "root" node is used to mark -entry points for the transformations. LLVMC also assigns a weight to each edge -(more on this later) to choose between several alternative edges.

    -

    The definition of the compilation graph (see file llvmc/src/Base.td for an -example) is just a list of edges:

    -
    -def CompilationGraph : CompilationGraph<[
    -    Edge<"root", "llvm_gcc_c">,
    -    Edge<"root", "llvm_gcc_assembler">,
    -    ...
    -
    -    Edge<"llvm_gcc_c", "llc">,
    -    Edge<"llvm_gcc_cpp", "llc">,
    -    ...
    -
    -    OptionalEdge<"llvm_gcc_c", "opt", (case (switch_on "opt"),
    -                                      (inc_weight))>,
    -    OptionalEdge<"llvm_gcc_cpp", "opt", (case (switch_on "opt"),
    -                                              (inc_weight))>,
    -    ...
    -
    -    OptionalEdge<"llvm_gcc_assembler", "llvm_gcc_cpp_linker",
    -        (case (input_languages_contain "c++"), (inc_weight),
    -              (or (parameter_equals "linker", "g++"),
    -                  (parameter_equals "linker", "c++")), (inc_weight))>,
    -    ...
    -
    -    ]>;
    -
    -

    As you can see, the edges can be either default or optional, where optional -edges are differentiated by an additional case expression used to calculate -the weight of this edge. Notice also that we refer to tools via their names (as -strings). This makes it possible to add edges to an existing compilation graph -without having to know about all tool definitions used in the graph.

    -

    The default edges are assigned a weight of 1, and optional edges get a weight of -0 + 2*N where N is the number of tests that evaluated to true in the case -expression. It is also possible to provide an integer parameter to -inc_weight and dec_weight - in this case, the weight is increased (or -decreased) by the provided value instead of the default 2. Default weight of an -optional edge can be changed by using the default clause of the case -construct.

    -

    When passing an input file through the graph, LLVMC picks the edge with the -maximum weight. To avoid ambiguity, there should be only one default edge -between two nodes (with the exception of the root node, which gets a special -treatment - there you are allowed to specify one default edge per language).

    -

    When multiple compilation graphs are defined, they are merged together. Multiple -edges with the same end nodes are not allowed (i.e. the graph is not a -multigraph), and will lead to a compile-time error.

    -

    To get a visual representation of the compilation graph (useful for debugging), -run llvmc --view-graph. You will need dot and gsview installed for -this to work properly.

    -
    -
    -

    Describing options

    -

    Command-line options supported by the driver are defined by using an -OptionList:

    -
    -def Options : OptionList<[
    -(switch_option "E", (help "Help string")),
    -(alias_option "quiet", "q")
    -...
    -]>;
    -
    -

    As you can see, the option list is just a list of DAGs, where each DAG is an -option description consisting of the option name and some properties. More than -one option list can be defined (they are all merged together in the end), which -can be handy if one wants to separate option groups syntactically.

    -
      -
    • Possible option types:

      -
      -
        -
      • switch_option - a simple boolean switch without arguments, for example --O2 or -time. At most one occurrence is allowed by default.
      • -
      • parameter_option - option that takes one argument, for example --std=c99. It is also allowed to use spaces instead of the equality -sign: -std c99. At most one occurrence is allowed.
      • -
      • parameter_list_option - same as the above, but more than one option -occurrence is allowed.
      • -
      • prefix_option - same as the parameter_option, but the option name and -argument do not have to be separated. Example: -ofile. This can be also -specified as -o file; however, -o=file will be parsed incorrectly -(=file will be interpreted as option value). At most one occurrence is -allowed.
      • -
      • prefix_list_option - same as the above, but more than one occurrence of -the option is allowed; example: -lm -lpthread.
      • -
      • alias_option - a special option type for creating aliases. Unlike other -option types, aliases are not allowed to have any properties besides the -aliased option name. -Usage example: (alias_option "preprocess", "E")
      • -
      • switch_list_option - like switch_option with the zero_or_more -property, but remembers how many times the switch was turned on. Useful -mostly for forwarding. Example: when -foo is a switch option (with the -zero_or_more property), the command driver -foo -foo is forwarded -as some-tool -foo, but when -foo is a switch list, the same command -is forwarded as some-tool -foo -foo.
      • -
      -
      -
    • -
    • Possible option properties:

      -
      -
        -
      • help - help string associated with this option. Used for --help -output.
      • -
      • required - this option must be specified exactly once (or, in case of -the list options without the multi_val property, at least -once). Incompatible with optional and one_or_more.
      • -
      • optional - the option can be specified either zero times or exactly -once. The default for switch options. Useful only for list options in -conjunction with multi_val. Incompatible with required, -zero_or_more and one_or_more.
      • -
      • one_or_more - the option must be specified at least once. Can be useful -to allow switch options be both obligatory and be specified multiple -times. For list options is useful only in conjunction with multi_val; -for ordinary it is synonymous with required. Incompatible with -required, optional and zero_or_more.
      • -
      • zero_or_more - the option can be specified zero or more times. Useful -to allow a single switch option to be specified more than -once. Incompatible with required, optional and one_or_more.
      • -
      • hidden - the description of this option will not appear in -the --help output (but will appear in the --help-hidden -output).
      • -
      • really_hidden - the option will not be mentioned in any help -output.
      • -
      • comma_separated - Indicates that any commas specified for an option's -value should be used to split the value up into multiple values for the -option. This property is valid only for list options. In conjunction with -forward_value can be used to implement option forwarding in style of -gcc's -Wa,.
      • -
      • multi_val n - this option takes n arguments (can be useful in some -special cases). Usage example: (parameter_list_option "foo", (multi_val -3)); the command-line syntax is '-foo a b c'. Only list options can have -this attribute; you can, however, use the one_or_more, optional -and required properties.
      • -
      • init - this option has a default value, either a string (if it is a -parameter), or a boolean (if it is a switch; as in C++, boolean constants -are called true and false). List options can't have init -attribute. -Usage examples: (switch_option "foo", (init true)); (prefix_option -"bar", (init "baz")).
      • -
      -
      -
    • -
    -
    -
    -

    Conditional evaluation

    -

    The 'case' construct is the main means by which programmability is achieved in -LLVMC. It can be used to calculate edge weights, program actions and modify the -shell commands to be executed. The 'case' expression is designed after the -similarly-named construct in functional languages and takes the form (case -(test_1), statement_1, (test_2), statement_2, ... (test_N), statement_N). The -statements are evaluated only if the corresponding tests evaluate to true.

    -

    Examples:

    -
    -// Edge weight calculation
    -
    -// Increases edge weight by 5 if "-A" is provided on the
    -// command-line, and by 5 more if "-B" is also provided.
    -(case
    -    (switch_on "A"), (inc_weight 5),
    -    (switch_on "B"), (inc_weight 5))
    -
    -
    -// Tool command line specification
    -
    -// Evaluates to "cmdline1" if the option "-A" is provided on the
    -// command line; to "cmdline2" if "-B" is provided;
    -// otherwise to "cmdline3".
    -
    -(case
    -    (switch_on "A"), "cmdline1",
    -    (switch_on "B"), "cmdline2",
    -    (default), "cmdline3")
    -
    -

    Note the slight difference in 'case' expression handling in contexts of edge -weights and command line specification - in the second example the value of the -"B" switch is never checked when switch "A" is enabled, and the whole -expression always evaluates to "cmdline1" in that case.

    -

    Case expressions can also be nested, i.e. the following is legal:

    -
    -(case (switch_on "E"), (case (switch_on "o"), ..., (default), ...)
    -      (default), ...)
    -
    -

    You should, however, try to avoid doing that because it hurts readability. It is -usually better to split tool descriptions and/or use TableGen inheritance -instead.

    -
      -
    • Possible tests are:
        -
      • switch_on - Returns true if a given command-line switch is provided by -the user. Can be given multiple arguments, in that case (switch_on "foo", -"bar", "baz") is equivalent to (and (switch_on "foo"), (switch_on -"bar"), (switch_on "baz")). -Example: (switch_on "opt").
      • -
      • any_switch_on - Given a number of switch options, returns true if any of -the switches is turned on. -Example: (any_switch_on "foo", "bar", "baz") is equivalent to (or -(switch_on "foo"), (switch_on "bar"), (switch_on "baz")).
      • -
      • parameter_equals - Returns true if a command-line parameter (first -argument) equals a given value (second argument). -Example: (parameter_equals "W", "all").
      • -
      • element_in_list - Returns true if a command-line parameter list (first -argument) contains a given value (second argument). -Example: (element_in_list "l", "pthread").
      • -
      • input_languages_contain - Returns true if a given language -belongs to the current input language set. -Example: (input_languages_contain "c++").
      • -
      • in_language - Evaluates to true if the input file language is equal to -the argument. At the moment works only with command and actions (on -non-join nodes). -Example: (in_language "c++").
      • -
      • not_empty - Returns true if a given option (which should be either a -parameter or a parameter list) is set by the user. Like switch_on, can -be also given multiple arguments. -Examples: (not_empty "o"), (not_empty "o", "l").
      • -
      • any_not_empty - Returns true if not_empty returns true for any of -the provided options. -Example: (any_not_empty "foo", "bar", "baz") is equivalent to (or -(not_empty "foo"), (not_empty "bar"), (not_empty "baz")).
      • -
      • empty - The opposite of not_empty. Equivalent to (not (not_empty -X)). Can be given multiple arguments.
      • -
      • any_not_empty - Returns true if not_empty returns true for any of -the provided options. -Example: (any_empty "foo", "bar", "baz") is equivalent to (or -(not_empty "foo"), (not_empty "bar"), (not_empty "baz")).
      • -
      • single_input_file - Returns true if there was only one input file -provided on the command-line. Used without arguments: -(single_input_file).
      • -
      • multiple_input_files - Equivalent to (not (single_input_file)) (the -case of zero input files is considered an error).
      • -
      • default - Always evaluates to true. Should always be the last -test in the case expression.
      • -
      • and - A standard logical combinator that returns true iff all of -its arguments return true. Used like this: (and (test1), (test2), -... (testN)). Nesting of and and or is allowed, but not -encouraged.
      • -
      • or - A logical combinator that returns true iff any of its arguments -return true. -Example: (or (test1), (test2), ... (testN)).
      • -
      • not - Standard unary logical combinator that negates its -argument. -Example: (not (or (test1), (test2), ... (testN))).
      • -
      -
    • -
    -
    -
    -

    Writing a tool description

    -

    As was said earlier, nodes in the compilation graph represent tools, which are -described separately. A tool definition looks like this (taken from the -llvmc/src/Base.td file):

    -
    -def llvm_gcc_cpp : Tool<[
    -    (in_language "c++"),
    -    (out_language "llvm-assembler"),
    -    (output_suffix "bc"),
    -    (command "llvm-g++ -c -emit-llvm"),
    -    (sink)
    -    ]>;
    -
    -

    This defines a new tool called llvm_gcc_cpp, which is an alias for -llvm-g++. As you can see, a tool definition is just a list of properties; -most of them should be self-explanatory. The sink property means that this -tool should be passed all command-line options that aren't mentioned in the -option list.

    -

    The complete list of all currently implemented tool properties follows.

    -
      -
    • Possible tool properties:
        -
      • in_language - input language name. Can be given multiple arguments, in -case the tool supports multiple input languages. Used for typechecking and -mapping file extensions to tools.
      • -
      • out_language - output language name. Multiple output languages are -allowed. Used for typechecking the compilation graph.
      • -
      • output_suffix - output file suffix. Can also be changed dynamically, see -documentation on actions.
      • -
      -
    • -
    -
    -
      -
    • command - the actual command used to run the tool. You can use output -redirection with >, hook invocations ($CALL), environment variables -(via $ENV) and the case construct.
    • -
    • join - this tool is a "join node" in the graph, i.e. it gets a list of -input files and joins them together. Used for linkers.
    • -
    • sink - all command-line options that are not handled by other tools are -passed to this tool.
    • -
    • actions - A single big case expression that specifies how this tool -reacts on command-line options (described in more detail below).
    • -
    -
    -
    -
      -
    • out_file_option, in_file_option - Options appended to the -command string to designate output and input files. Default values are -"-o" and "", respectively.
    • -
    -
    -
    -

    Actions

    -

    A tool often needs to react to command-line options, and this is precisely what -the actions property is for. The next example illustrates this feature:

    -
    -def llvm_gcc_linker : Tool<[
    -    (in_language "object-code"),
    -    (out_language "executable"),
    -    (output_suffix "out"),
    -    (command "llvm-gcc"),
    -    (join),
    -    (actions (case (not_empty "L"), (forward "L"),
    -                   (not_empty "l"), (forward "l"),
    -                   (not_empty "dummy"),
    -                             [(append_cmd "-dummy1"), (append_cmd "-dummy2")])
    -    ]>;
    -
    -

    The actions tool property is implemented on top of the omnipresent case -expression. It associates one or more different actions with given -conditions - in the example, the actions are forward, which forwards a given -option unchanged, and append_cmd, which appends a given string to the tool -execution command. Multiple actions can be associated with a single condition by -using a list of actions (used in the example to append some dummy options). The -same case construct can also be used in the cmd_line property to modify -the tool command line.

    -

    The "join" property used in the example means that this tool behaves like a -linker.

    -

    The list of all possible actions follows.

    -
      -
    • Possible actions:

      -
      -
        -
      • append_cmd - Append a string to the tool invocation command. -Example: (case (switch_on "pthread"), (append_cmd "-lpthread")).
      • -
      • error - Exit with error. -Example: (error "Mixing -c and -S is not allowed!").
      • -
      • warning - Print a warning. -Example: (warning "Specifying both -O1 and -O2 is meaningless!").
      • -
      • forward - Forward the option unchanged. -Example: (forward "Wall").
      • -
      • forward_as - Change the option's name, but forward the argument -unchanged. -Example: (forward_as "O0", "--disable-optimization").
      • -
      • forward_value - Forward only option's value. Cannot be used with switch -options (since they don't have values), but works fine with lists. -Example: (forward_value "Wa,").
      • -
      • forward_transformed_value - As above, but applies a hook to the -option's value before forwarding (see below). When -forward_transformed_value is applied to a list -option, the hook must have signature -std::string hooks::HookName (const std::vector<std::string>&). -Example: (forward_transformed_value "m", "ConvertToMAttr").
      • -
      • output_suffix - Modify the output suffix of this tool. -Example: (output_suffix "i").
      • -
      • stop_compilation - Stop compilation after this tool processes its -input. Used without arguments. -Example: (stop_compilation).
      • -
      -
      -
    • -
    -
    -
    -
    -

    Language map

    -

    If you are adding support for a new language to LLVMC, you'll need to modify the -language map, which defines mappings from file extensions to language names. It -is used to choose the proper toolchain(s) for a given input file set. Language -map definition looks like this:

    -
    -def LanguageMap : LanguageMap<
    -    [LangToSuffixes<"c++", ["cc", "cp", "cxx", "cpp", "CPP", "c++", "C"]>,
    -     LangToSuffixes<"c", ["c"]>,
    -     ...
    -    ]>;
    -
    -

    For example, without those definitions the following command wouldn't work:

    -
    -$ llvmc hello.cpp
    -llvmc: Unknown suffix: cpp
    -
    -

    The language map entries are needed only for the tools that are linked from the -root node. A tool can have multiple output languages.

    -
    -
    -

    Option preprocessor

    -

    It is sometimes useful to run error-checking code before processing the -compilation graph. For example, if optimization options "-O1" and "-O2" are -implemented as switches, we might want to output a warning if the user invokes -the driver with both of these options enabled.

    -

    The OptionPreprocessor feature is reserved specially for these -occasions. Example (adapted from llvm/src/Base.td.in):

    -
    -def Preprocess : OptionPreprocessor<
    -(case (not (any_switch_on "O0", "O1", "O2", "O3")),
    -           (set_option "O2"),
    -      (and (switch_on "O3"), (any_switch_on "O0", "O1", "O2")),
    -           (unset_option "O0", "O1", "O2"),
    -      (and (switch_on "O2"), (any_switch_on "O0", "O1")),
    -           (unset_option "O0", "O1"),
    -      (and (switch_on "O1"), (switch_on "O0")),
    -           (unset_option "O0"))
    ->;
    -
    -

    Here, OptionPreprocessor is used to unset all spurious -O options so -that they are not forwarded to the compiler. If no optimization options are -specified, -O2 is enabled.

    -

    OptionPreprocessor is basically a single big case expression, which is -evaluated only once right after the driver is started. The only allowed actions -in OptionPreprocessor are error, warning, and two special actions: -unset_option and set_option. As their names suggest, they can be used to -set or unset a given option. To set an option with set_option, use the -two-argument form: (set_option "parameter", VALUE). Here, VALUE can be -either a string, a string list, or a boolean constant.

    -

    For convenience, set_option and unset_option also work with multiple -arguments. That is, instead of [(unset_option "A"), (unset_option "B")] you -can use (unset_option "A", "B"). Obviously, (set_option "A", "B") is -only valid if both A and B are switches.

    -
    -
    -

    More advanced topics

    -
    -

    Hooks and environment variables

    -

    Normally, LLVMC searches for programs in the system PATH. Sometimes, this is -not sufficient: for example, we may want to specify tool paths or names in the -configuration file. This can be achieved via the hooks mechanism. To write your -own hooks, add their definitions to the Hooks.cpp or drop a .cpp file -into your driver directory. Hooks should live in the hooks namespace and -have the signature std::string hooks::MyHookName ([const char* Arg0 [ const -char* Arg2 [, ...]]]). They can be used from the command tool property:

    -
    -(command "$CALL(MyHook)/path/to/file -o $CALL(AnotherHook)")
    -
    -

    To pass arguments to hooks, use the following syntax:

    -
    -(command "$CALL(MyHook, 'Arg1', 'Arg2', 'Arg # 3')/path/to/file -o1 -o2")
    -
    -

    It is also possible to use environment variables in the same manner:

    -
    -(command "$ENV(VAR1)/path/to/file -o $ENV(VAR2)")
    -
    -

    To change the command line string based on user-provided options use -the case expression (documented above):

    -
    -(command
    -  (case
    -    (switch_on "E"),
    -       "llvm-g++ -E -x c $INFILE -o $OUTFILE",
    -    (default),
    -       "llvm-g++ -c -x c $INFILE -o $OUTFILE -emit-llvm"))
    -
    -
    -
    -

    Debugging

    -

    When writing LLVMC-based drivers, it can be useful to get a visual view of the -resulting compilation graph. This can be achieved via the command line option ---view-graph (which assumes that Graphviz and Ghostview are -installed). There is also a --write-graph option that creates a Graphviz -source file (compilation-graph.dot) in the current directory.

    -

    Another useful llvmc option is --check-graph. It checks the compilation -graph for common errors like mismatched output/input language names, multiple -default edges and cycles. When invoked with --check-graph, llvmc doesn't -perform any compilation tasks and returns the number of encountered errors as -its status code. In the future, these checks will be performed at compile-time -and this option will disappear.

    -
    -
    -

    Conditioning on the executable name

    -

    For now, the executable name (the value passed to the driver in argv[0]) is -accessible only in the C++ code (i.e. hooks). Use the following code:

    -
    -namespace llvmc {
    -extern const char* ProgramName;
    -}
    -
    -namespace hooks {
    -
    -std::string MyHook() {
    -//...
    -if (strcmp(ProgramName, "mydriver") == 0) {
    -   //...
    -
    -}
    -
    -} // end namespace hooks
    -
    -

    In general, you're encouraged not to make the behaviour dependent on the -executable file name, and use command-line switches instead. See for example how -the llvmc program behaves when it needs to choose the correct linker options -(think g++ vs. gcc).

    -
    -
    - -Valid CSS - -Valid XHTML 1.0 Transitional - -Mikhail Glushenkov
    -LLVM Compiler Infrastructure
    - -Last modified: $Date$ -
    -
    -
    - - diff --git a/docs/CompilerDriverTutorial.html b/docs/CompilerDriverTutorial.html deleted file mode 100644 index 4ed373aa160..00000000000 --- a/docs/CompilerDriverTutorial.html +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - -Tutorial - Using LLVMC - - - -
    -

    Tutorial - Using LLVMC

    - - - -
    -

    Written by Mikhail Glushenkov

    -
    -

    Introduction

    -

    LLVMC is a generic compiler driver, which plays the same role for LLVM as the -gcc program does for GCC - the difference being that LLVMC is designed to be -more adaptable and easier to customize. Most of LLVMC functionality is -implemented via high-level TableGen code, from which a corresponding C++ source -file is automatically generated. This tutorial describes the basic usage and -configuration of LLVMC.

    -
    -
    -

    Using the llvmc program

    -

    In general, llvmc tries to be command-line compatible with gcc as much -as possible, so most of the familiar options work:

    -
    -$ llvmc -O3 -Wall hello.cpp
    -$ ./a.out
    -hello
    -
    -

    This will invoke llvm-g++ under the hood (you can see which commands are -executed by using the -v option). For further help on command-line LLVMC -usage, refer to the llvmc --help output.

    -
    -
    -

    Using LLVMC to generate toolchain drivers

    -

    LLVMC-based drivers are written mostly using TableGen, so you need to be -familiar with it to get anything done.

    -

    Start by compiling example/Simple, which is a primitive wrapper for -gcc:

    -
    -$ cd $LLVM_OBJ_DIR/tools/examples/Simple
    -$ make
    -$ cat > hello.c
    -#include <stdio.h>
    -int main() { printf("Hello\n"); }
    -$ $LLVM_BIN_DIR/Simple -v hello.c
    -gcc hello.c -o hello.out
    -$ ./hello.out
    -Hello
    -
    -

    We have thus produced a simple driver called, appropriately, Simple, from -the input TableGen file Simple.td. The llvmc program itself is generated -using a similar process (see llvmc/src). Contents of the file Simple.td -look like this:

    -
    -// Include common definitions
    -include "llvm/CompilerDriver/Common.td"
    -
    -// Tool descriptions
    -def gcc : Tool<
    -[(in_language "c"),
    - (out_language "executable"),
    - (output_suffix "out"),
    - (command "gcc"),
    - (sink),
    -
    - // -o is what is used by default, out_file_option here is included for
    - // instructive purposes.
    - (out_file_option "-o")
    -]>;
    -
    -// Language map
    -def LanguageMap : LanguageMap<[(lang_to_suffixes "c", "c")]>;
    -
    -// Compilation graph
    -def CompilationGraph : CompilationGraph<[(edge "root", "gcc")]>;
    -
    -

    As you can see, this file consists of three parts: tool descriptions, language -map, and the compilation graph definition.

    -

    At the heart of LLVMC is the idea of a compilation graph: vertices in this graph -are tools, and edges represent a transformation path between two tools (for -example, assembly source produced by the compiler can be transformed into -executable code by an assembler). The compilation graph is basically a list of -edges; a special node named root is used to mark graph entry points.

    -

    Tool descriptions are represented as property lists: most properties in the -example above should be self-explanatory; the sink property means that all -options lacking an explicit description should be forwarded to this tool.

    -

    The LanguageMap associates a language name with a list of suffixes and is -used for deciding which toolchain corresponds to a given input file.

    -

    To learn more about writing your own drivers with LLVMC, refer to the reference -manual and examples in the examples directory. Of a particular interest is -the Skeleton example, which can serve as a template for your LLVMC-based -drivers.

    -
    -
    - -Valid CSS - -Valid XHTML 1.0 Transitional - -Mikhail Glushenkov
    -LLVM Compiler Infrastructure
    - -Last modified: $Date: 2008-12-11 11:34:48 -0600 (Thu, 11 Dec 2008) $ -
    -
    - - diff --git a/docs/FAQ.html b/docs/FAQ.html index 620cf2500a4..9e3ea7f2a8d 100644 --- a/docs/FAQ.html +++ b/docs/FAQ.html @@ -540,10 +540,7 @@ Stop.

    Currently, there isn't much. LLVM supports an intermediate representation which is useful for code representation but will not support the high level (abstract syntax tree) representation needed by most compilers. There are no - facilities for lexical nor semantic analysis. There is, however, a mostly - implemented configuration-driven - compiler driver which simplifies the task - of running optimizations, linking, and executable generation.

    + facilities for lexical nor semantic analysis.

    diff --git a/docs/index.html b/docs/index.html index fa9f1fae0fc..422dfb2347f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -216,14 +216,6 @@ in LLVM.
  • Bugpoint - automatic bug finder and test-case reducer description and usage information.
  • -
  • Compiler Driver (llvmc) Tutorial -- This document is a tutorial introduction to the usage and -configuration of the LLVM compiler driver tool, llvmc.
  • - -
  • Compiler Driver (llvmc) -Reference - This document describes the design and configuration -of llvmc in more detail.
  • -
  • LLVM Bitcode File Format - This describes the file format and encoding used for LLVM "bc" files.
  • diff --git a/include/llvm/CompilerDriver/Action.h b/include/llvm/CompilerDriver/Action.h deleted file mode 100644 index f2b79655f60..00000000000 --- a/include/llvm/CompilerDriver/Action.h +++ /dev/null @@ -1,54 +0,0 @@ -//===--- Action.h - The LLVM Compiler Driver --------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Action - encapsulates a single shell command. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_ACTION_H -#define LLVM_INCLUDE_COMPILER_DRIVER_ACTION_H - -#include -#include - -namespace llvmc { - - typedef std::vector StrVector; - - /// Action - A class that encapsulates a single shell command. - class Action { - /// Command_ - The actual command (for example, 'ls'). - std::string Command_; - /// Args_ - Command arguments. Stdout redirection ("> file") is allowed. - std::vector Args_; - /// StopCompilation_ - Should we stop compilation after executing - /// this action? - bool StopCompilation_; - /// OutFile_ - The output file name. - std::string OutFile_; - - public: - void Construct (const std::string& C, const StrVector& A, - bool S, const std::string& O) { - Command_ = C; - Args_ = A; - StopCompilation_ = S; - OutFile_ = O; - } - bool IsConstructed () { return (Command_.size() != 0);} - - /// Execute - Executes the command. Returns -1 on error. - int Execute () const; - bool StopCompilation () const { return StopCompilation_; } - const std::string& OutFile() { return OutFile_; } - }; - -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_ACTION_H diff --git a/include/llvm/CompilerDriver/AutoGenerated.h b/include/llvm/CompilerDriver/AutoGenerated.h deleted file mode 100644 index 7b926c622c9..00000000000 --- a/include/llvm/CompilerDriver/AutoGenerated.h +++ /dev/null @@ -1,40 +0,0 @@ -//===--- AutoGenerated.h - The LLVM Compiler Driver -------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Interface to the autogenerated driver code. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_AUTOGENERATED_H -#define LLVM_INCLUDE_COMPILER_DRIVER_AUTOGENERATED_H - -namespace llvmc { - class LanguageMap; - class CompilationGraph; - - namespace autogenerated { - - int PreprocessOptions(); - int PopulateLanguageMap(LanguageMap& langMap); - int PopulateCompilationGraph(CompilationGraph& graph); - - inline int RunInitialization (LanguageMap& M, CompilationGraph& G) { - if (int ret = PreprocessOptions()) - return ret; - if (int ret = PopulateLanguageMap(M)) - return ret; - if (int ret = PopulateCompilationGraph(G)) - return ret; - - return 0; - } - } -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_AUTOGENERATED_H diff --git a/include/llvm/CompilerDriver/BuiltinOptions.h b/include/llvm/CompilerDriver/BuiltinOptions.h deleted file mode 100644 index 7b9c15c52f7..00000000000 --- a/include/llvm/CompilerDriver/BuiltinOptions.h +++ /dev/null @@ -1,39 +0,0 @@ -//===--- BuiltinOptions.h - The LLVM Compiler Driver ------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Declarations of all global command-line option variables. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H -#define LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H - -#include "llvm/Support/CommandLine.h" - -#include - -namespace llvmc { - -namespace SaveTempsEnum { enum Values { Cwd, Obj, Unset }; } - -extern llvm::cl::list InputFilenames; -extern llvm::cl::opt OutputFilename; -extern llvm::cl::opt TempDirname; -extern llvm::cl::list Languages; -extern llvm::cl::opt DryRun; -extern llvm::cl::opt Time; -extern llvm::cl::opt VerboseMode; -extern llvm::cl::opt CheckGraph; -extern llvm::cl::opt ViewGraph; -extern llvm::cl::opt WriteGraph; -extern llvm::cl::opt SaveTemps; - -} // End namespace llvmc. - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_BUILTIN_OPTIONS_H diff --git a/include/llvm/CompilerDriver/Common.td b/include/llvm/CompilerDriver/Common.td deleted file mode 100644 index 6ba30aaa640..00000000000 --- a/include/llvm/CompilerDriver/Common.td +++ /dev/null @@ -1,127 +0,0 @@ -//===- Common.td - Common definitions for LLVMC2 ----------*- tablegen -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file contains common definitions used in llvmc tool description files. -// -//===----------------------------------------------------------------------===// - -class Tool l> { - list properties = l; -} - -// Possible Tool properties. - -def in_language; -def out_language; -def output_suffix; -def command; -def out_file_option; -def in_file_option; -def join; -def sink; -def works_on_empty; -def actions; - -// Possible option types. - -def alias_option; -def switch_option; -def switch_list_option; -def parameter_option; -def parameter_list_option; -def prefix_option; -def prefix_list_option; - -// Possible option properties. - -def help; -def hidden; -def init; -def multi_val; -def one_or_more; -def zero_or_more; -def optional; -def really_hidden; -def required; -def comma_separated; -def forward_not_split; - -// The 'case' construct. -def case; - -// Boolean constants. -class Bool { - bit Value = val; -} -def true : Bool<1>; -def false : Bool<0>; - -// Boolean operators. -def and; -def or; -def not; - -// Primitive tests. -def switch_on; -def parameter_equals; -def element_in_list; -def input_languages_contain; -def empty; -def not_empty; -def default; -def single_input_file; -def multiple_input_files; -def any_switch_on; -def any_not_empty; -def any_empty; - -// Possible actions. - -def append_cmd; -def forward; -def forward_as; -def forward_value; -def forward_transformed_value; -def stop_compilation; -def no_out_file; -def unpack_values; -def warning; -def error; -def set_option; -def unset_option; - -// Increase the edge weight. -def inc_weight; - -// Option list - a single place to specify options. -class OptionList l> { - list options = l; -} - -// Option preprocessor - actions taken during plugin loading. -class OptionPreprocessor { - dag preprocessor = d; -} - -// Map from suffixes to language names - -def lang_to_suffixes; - -class LanguageMap l> { - list map = l; -} - -// Compilation graph - -def edge; -def optional_edge; - -class CompilationGraph l> { - list edges = l; -} diff --git a/include/llvm/CompilerDriver/CompilationGraph.h b/include/llvm/CompilerDriver/CompilationGraph.h deleted file mode 100644 index 951aff6f938..00000000000 --- a/include/llvm/CompilerDriver/CompilationGraph.h +++ /dev/null @@ -1,330 +0,0 @@ -//===--- CompilationGraph.h - The LLVM Compiler Driver ----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Compilation graph - definition. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_COMPILATION_GRAPH_H -#define LLVM_INCLUDE_COMPILER_DRIVER_COMPILATION_GRAPH_H - -#include "llvm/CompilerDriver/Tool.h" - -#include "llvm/ADT/GraphTraits.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringSet.h" -#include "llvm/Support/Path.h" - -#include -#include - -namespace llvmc { - - class CompilationGraph; - typedef llvm::StringSet<> InputLanguagesSet; - - /// LanguageMap - Maps from extensions to language names. - class LanguageMap : public llvm::StringMap { - public: - - /// GetLanguage - Find the language name corresponding to a given file. - const std::string* GetLanguage(const llvm::sys::Path&) const; - }; - - /// Edge - Represents an edge of the compilation graph. - class Edge : public llvm::RefCountedBaseVPTR { - public: - Edge(const std::string& T) : ToolName_(T) {} - virtual ~Edge() {} - - const std::string& ToolName() const { return ToolName_; } - virtual int Weight(const InputLanguagesSet& InLangs) const = 0; - private: - std::string ToolName_; - }; - - /// SimpleEdge - An edge that has no properties. - class SimpleEdge : public Edge { - public: - SimpleEdge(const std::string& T) : Edge(T) {} - int Weight(const InputLanguagesSet&) const { return 1; } - }; - - /// Node - A node (vertex) of the compilation graph. - struct Node { - // A Node holds a list of the outward edges. - typedef llvm::SmallVector, 3> container_type; - typedef container_type::iterator iterator; - typedef container_type::const_iterator const_iterator; - - Node() : OwningGraph(0), InEdges(0) {} - Node(CompilationGraph* G) : OwningGraph(G), InEdges(0) {} - Node(CompilationGraph* G, Tool* T) : - OwningGraph(G), ToolPtr(T), InEdges(0) {} - - bool HasChildren() const { return !OutEdges.empty(); } - const std::string Name() const - { return ToolPtr ? ToolPtr->Name() : "root"; } - - // Iteration. - iterator EdgesBegin() { return OutEdges.begin(); } - const_iterator EdgesBegin() const { return OutEdges.begin(); } - iterator EdgesEnd() { return OutEdges.end(); } - const_iterator EdgesEnd() const { return OutEdges.end(); } - - /// AddEdge - Add an outward edge. Takes ownership of the provided - /// Edge object. - void AddEdge(Edge* E); - - // Inward edge counter. Used to implement topological sort. - void IncrInEdges() { ++InEdges; } - void DecrInEdges() { --InEdges; } - bool HasNoInEdges() const { return InEdges == 0; } - - // Needed to implement NodeChildIterator/GraphTraits - CompilationGraph* OwningGraph; - // The corresponding Tool. - // WARNING: ToolPtr can be NULL (for the root node). - llvm::IntrusiveRefCntPtr ToolPtr; - // Links to children. - container_type OutEdges; - // Inward edge counter. Updated in - // CompilationGraph::insertEdge(). Used for topological sorting. - unsigned InEdges; - }; - - class NodesIterator; - - /// CompilationGraph - The compilation graph itself. - class CompilationGraph { - /// nodes_map_type - The main data structure. - typedef llvm::StringMap nodes_map_type; - /// tools_vector_type, tools_map_type - Data structures used to - /// map from language names to tools. (We can have several tools - /// associated with each language name, hence the need for a - /// vector.) - typedef - llvm::SmallVector, 3> tools_vector_type; - typedef llvm::StringMap tools_map_type; - - /// ToolsMap - Map from language names to lists of tool names. - tools_map_type ToolsMap; - /// NodesMap - Map from tool names to Tool objects. - nodes_map_type NodesMap; - - public: - - typedef nodes_map_type::iterator nodes_iterator; - typedef nodes_map_type::const_iterator const_nodes_iterator; - - CompilationGraph(); - - /// insertNode - Insert a new node into the graph. Takes - /// ownership of the object. - void insertNode(Tool* T); - - /// insertEdge - Insert a new edge into the graph. Takes ownership - /// of the Edge object. Returns non-zero value on error. - int insertEdge(const std::string& A, Edge* E); - - /// Build - Build target(s) from the input file set. Command-line options - /// are passed implicitly as global variables. Returns non-zero value on - /// error (usually the failed program's exit code). - int Build(llvm::sys::Path const& TempDir, const LanguageMap& LangMap); - - /// Check - Check the compilation graph for common errors like cycles, - /// input/output language mismatch and multiple default edges. Prints error - /// messages and in case it finds any errors. - int Check(); - - /// getNode - Return a reference to the node corresponding to the given tool - /// name. Returns 0 on error. - Node* getNode(const std::string& ToolName); - const Node* getNode(const std::string& ToolName) const; - - /// viewGraph - This function is meant for use from the debugger. You can - /// just say 'call G->viewGraph()' and a ghostview window should pop up from - /// the program, displaying the compilation graph. This depends on there - /// being a 'dot' and 'gv' program in your path. - void viewGraph(); - - /// writeGraph - Write Graphviz .dot source file to the current direcotry. - int writeGraph(const std::string& OutputFilename); - - // GraphTraits support. - friend NodesIterator GraphBegin(CompilationGraph*); - friend NodesIterator GraphEnd(CompilationGraph*); - - private: - // Helper functions. - - /// getToolsVector - Return a reference to the list of tool names - /// corresponding to the given language name. Returns 0 on error. - const tools_vector_type* getToolsVector(const std::string& LangName) const; - - /// PassThroughGraph - Pass the input file through the toolchain starting at - /// StartNode. - int PassThroughGraph (const llvm::sys::Path& In, const Node* StartNode, - const InputLanguagesSet& InLangs, - const llvm::sys::Path& TempDir, - const LanguageMap& LangMap) const; - - /// FindToolChain - Find head of the toolchain corresponding to - /// the given file. - const Node* FindToolChain(const llvm::sys::Path& In, - const std::string* ForceLanguage, - InputLanguagesSet& InLangs, - const LanguageMap& LangMap) const; - - /// BuildInitial - Traverse the initial parts of the toolchains. Returns - /// non-zero value on error. - int BuildInitial(InputLanguagesSet& InLangs, - const llvm::sys::Path& TempDir, - const LanguageMap& LangMap); - - /// TopologicalSort - Sort the nodes in topological order. Returns non-zero - /// value on error. - int TopologicalSort(std::vector& Out); - /// TopologicalSortFilterJoinNodes - Call TopologicalSort and filter the - /// resulting list to include only Join nodes. Returns non-zero value on - /// error. - int TopologicalSortFilterJoinNodes(std::vector& Out); - - // Functions used to implement Check(). - - /// CheckLanguageNames - Check that output/input language names match for - /// all nodes. Returns non-zero value on error (number of errors - /// encountered). - int CheckLanguageNames() const; - /// CheckMultipleDefaultEdges - check that there are no multiple default - /// default edges. Returns non-zero value on error (number of errors - /// encountered). - int CheckMultipleDefaultEdges() const; - /// CheckCycles - Check that there are no cycles in the graph. Returns - /// non-zero value on error (number of errors encountered). - int CheckCycles(); - - }; - - // GraphTraits support code. - - /// NodesIterator - Auxiliary class needed to implement GraphTraits - /// support. Can be generalised to something like value_iterator - /// for map-like containers. - class NodesIterator : public CompilationGraph::nodes_iterator { - typedef CompilationGraph::nodes_iterator super; - typedef NodesIterator ThisType; - typedef Node* pointer; - typedef Node& reference; - - public: - NodesIterator(super I) : super(I) {} - - inline reference operator*() const { - return super::operator->()->second; - } - inline pointer operator->() const { - return &super::operator->()->second; - } - }; - - inline NodesIterator GraphBegin(CompilationGraph* G) { - return NodesIterator(G->NodesMap.begin()); - } - - inline NodesIterator GraphEnd(CompilationGraph* G) { - return NodesIterator(G->NodesMap.end()); - } - - - /// NodeChildIterator - Another auxiliary class needed by GraphTraits. - class NodeChildIterator : public - std::iterator { - typedef NodeChildIterator ThisType; - typedef Node::container_type::iterator iterator; - - CompilationGraph* OwningGraph; - iterator EdgeIter; - public: - typedef Node* pointer; - typedef Node& reference; - - NodeChildIterator(Node* N, iterator I) : - OwningGraph(N->OwningGraph), EdgeIter(I) {} - - const ThisType& operator=(const ThisType& I) { - assert(OwningGraph == I.OwningGraph); - EdgeIter = I.EdgeIter; - return *this; - } - - inline bool operator==(const ThisType& I) const { - assert(OwningGraph == I.OwningGraph); - return EdgeIter == I.EdgeIter; - } - inline bool operator!=(const ThisType& I) const { - return !this->operator==(I); - } - - inline pointer operator*() const { - return OwningGraph->getNode((*EdgeIter)->ToolName()); - } - inline pointer operator->() const { - return this->operator*(); - } - - ThisType& operator++() { ++EdgeIter; return *this; } // Preincrement - ThisType operator++(int) { // Postincrement - ThisType tmp = *this; - ++*this; - return tmp; - } - - inline ThisType& operator--() { --EdgeIter; return *this; } // Predecrement - inline ThisType operator--(int) { // Postdecrement - ThisType tmp = *this; - --*this; - return tmp; - } - - }; -} - -namespace llvm { - template <> - struct GraphTraits { - typedef llvmc::CompilationGraph GraphType; - typedef llvmc::Node NodeType; - typedef llvmc::NodeChildIterator ChildIteratorType; - - static NodeType* getEntryNode(GraphType* G) { - return G->getNode("root"); - } - - static ChildIteratorType child_begin(NodeType* N) { - return ChildIteratorType(N, N->OutEdges.begin()); - } - static ChildIteratorType child_end(NodeType* N) { - return ChildIteratorType(N, N->OutEdges.end()); - } - - typedef llvmc::NodesIterator nodes_iterator; - static nodes_iterator nodes_begin(GraphType *G) { - return GraphBegin(G); - } - static nodes_iterator nodes_end(GraphType *G) { - return GraphEnd(G); - } - }; - -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_COMPILATION_GRAPH_H diff --git a/include/llvm/CompilerDriver/Error.h b/include/llvm/CompilerDriver/Error.h deleted file mode 100644 index 013094e5dd7..00000000000 --- a/include/llvm/CompilerDriver/Error.h +++ /dev/null @@ -1,29 +0,0 @@ -//===--- Error.h - The LLVM Compiler Driver ---------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Error handling. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_ERROR_H -#define LLVM_INCLUDE_COMPILER_DRIVER_ERROR_H - -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/raw_ostream.h" - -namespace llvmc { - - inline void PrintError(llvm::StringRef Err) { - extern const char* ProgramName; - llvm::errs() << ProgramName << ": " << Err << '\n'; - } - -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_ERROR_H diff --git a/include/llvm/CompilerDriver/Main.h b/include/llvm/CompilerDriver/Main.h deleted file mode 100644 index d136a5d2fa1..00000000000 --- a/include/llvm/CompilerDriver/Main.h +++ /dev/null @@ -1,21 +0,0 @@ -//===--- Main.h - The LLVM Compiler Driver ----------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Entry point for the driver executable. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_MAIN_H -#define LLVM_INCLUDE_COMPILER_DRIVER_MAIN_H - -namespace llvmc { - int Main(int argc, char** argv); -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_MAIN_H diff --git a/include/llvm/CompilerDriver/Main.inc b/include/llvm/CompilerDriver/Main.inc deleted file mode 100644 index 41640437de8..00000000000 --- a/include/llvm/CompilerDriver/Main.inc +++ /dev/null @@ -1,23 +0,0 @@ -//===--- Main.inc - The LLVM Compiler Driver --------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Default main() for the driver executable. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_MAIN_INC -#define LLVM_INCLUDE_COMPILER_DRIVER_MAIN_INC - -#include "llvm/CompilerDriver/Main.h" - -int main(int argc, char** argv) { - return llvmc::Main(argc, argv); -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_MAIN_INC diff --git a/include/llvm/CompilerDriver/Tool.h b/include/llvm/CompilerDriver/Tool.h deleted file mode 100644 index 18a2b767923..00000000000 --- a/include/llvm/CompilerDriver/Tool.h +++ /dev/null @@ -1,100 +0,0 @@ -//===--- Tool.h - The LLVM Compiler Driver ----------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Tool abstract base class - an interface to tool descriptions. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_INCLUDE_COMPILER_DRIVER_TOOL_H -#define LLVM_INCLUDE_COMPILER_DRIVER_TOOL_H - -#include "llvm/CompilerDriver/Action.h" - -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/StringSet.h" -#include "llvm/Support/Path.h" - -#include -#include -#include - -namespace llvmc { - - class LanguageMap; - typedef std::vector > ArgsVector; - typedef std::vector PathVector; - typedef std::vector StrVector; - typedef llvm::StringSet<> InputLanguagesSet; - - /// Tool - Represents a single tool. - class Tool : public llvm::RefCountedBaseVPTR { - public: - - virtual ~Tool() {} - - /// GenerateAction - Generate an Action given particular command-line - /// options. Returns non-zero value on error. - virtual int GenerateAction (Action& Out, - const PathVector& inFiles, - const bool HasChildren, - const llvm::sys::Path& TempDir, - const InputLanguagesSet& InLangs, - const LanguageMap& LangMap) const = 0; - - /// GenerateAction - Generate an Action given particular command-line - /// options. Returns non-zero value on error. - virtual int GenerateAction (Action& Out, - const llvm::sys::Path& inFile, - const bool HasChildren, - const llvm::sys::Path& TempDir, - const InputLanguagesSet& InLangs, - const LanguageMap& LangMap) const = 0; - - virtual const char* Name() const = 0; - virtual const char** InputLanguages() const = 0; - virtual const char** OutputLanguages() const = 0; - - virtual bool IsJoin() const = 0; - virtual bool WorksOnEmpty() const = 0; - - protected: - /// OutFileName - Generate the output file name. - llvm::sys::Path OutFilename(const llvm::sys::Path& In, - const llvm::sys::Path& TempDir, - bool StopCompilation, - const char* OutputSuffix) const; - - StrVector SortArgs(ArgsVector& Args) const; - }; - - /// JoinTool - A Tool that has an associated input file list. - class JoinTool : public Tool { - public: - void AddToJoinList(const llvm::sys::Path& P) { JoinList_.push_back(P); } - void ClearJoinList() { JoinList_.clear(); } - bool JoinListEmpty() const { return JoinList_.empty(); } - - int GenerateAction(Action& Out, - const bool HasChildren, - const llvm::sys::Path& TempDir, - const InputLanguagesSet& InLangs, - const LanguageMap& LangMap) const { - return GenerateAction(Out, JoinList_, HasChildren, TempDir, InLangs, - LangMap); - } - // We shouldn't shadow base class's version of GenerateAction. - using Tool::GenerateAction; - - private: - PathVector JoinList_; - }; - -} - -#endif // LLVM_INCLUDE_COMPILER_DRIVER_TOOL_H diff --git a/lib/CompilerDriver/Action.cpp b/lib/CompilerDriver/Action.cpp deleted file mode 100644 index a8d625c7ac0..00000000000 --- a/lib/CompilerDriver/Action.cpp +++ /dev/null @@ -1,134 +0,0 @@ -//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Action class - implementation and auxiliary functions. -// -//===----------------------------------------------------------------------===// - -#include "llvm/CompilerDriver/Action.h" -#include "llvm/CompilerDriver/BuiltinOptions.h" -#include "llvm/CompilerDriver/Error.h" -#include "llvm/CompilerDriver/Main.h" - -#include "llvm/Support/raw_ostream.h" -#include "llvm/Support/SystemUtils.h" -#include "llvm/Support/Program.h" -#include "llvm/Support/TimeValue.h" - -#include -#include - -using namespace llvm; -using namespace llvmc; - -namespace llvmc { - -extern const char* ProgramName; - -} - -namespace { - - void PrintString (const std::string& str) { - errs() << str << ' '; - } - - void PrintCommand (const std::string& Cmd, const StrVector& Args) { - errs() << Cmd << ' '; - std::for_each(Args.begin(), Args.end(), &PrintString); - errs() << '\n'; - } - - bool IsSegmentationFault (int returnCode) { -#ifdef LLVM_ON_WIN32 - return (returnCode >= 0xc0000000UL) -#else - return (returnCode < 0); -#endif - } - - int ExecuteProgram (const std::string& name, const StrVector& args) { - sys::Path prog(name); - - if (sys::path::is_relative(prog.str())) { - prog = PrependMainExecutablePath(name, ProgramName, - (void *)(intptr_t)&Main); - - if (!prog.canExecute()) { - prog = sys::Program::FindProgramByName(name); - if (prog.isEmpty()) { - PrintError("Can't find program '" + name + "'"); - return -1; - } - } - } - if (!prog.canExecute()) { - PrintError("Program '" + name + "' is not executable."); - return -1; - } - - // Build the command line vector and the redirects array. - const sys::Path* redirects[3] = {0,0,0}; - sys::Path stdout_redirect; - - std::vector argv; - argv.reserve((args.size()+2)); - argv.push_back(name.c_str()); - - for (StrVector::const_iterator B = args.begin(), E = args.end(); - B!=E; ++B) { - if (*B == ">") { - ++B; - stdout_redirect.set(*B); - redirects[1] = &stdout_redirect; - } - else { - argv.push_back((*B).c_str()); - } - } - argv.push_back(0); // null terminate list. - - // Invoke the program. - int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]); - - if (IsSegmentationFault(ret)) { - errs() << "Segmentation fault: "; - PrintCommand(name, args); - } - - return ret; - } -} - -namespace llvmc { - void AppendToGlobalTimeLog (const std::string& cmd, double time); -} - -int llvmc::Action::Execute () const { - if (DryRun || VerboseMode) - PrintCommand(Command_, Args_); - - if (!DryRun) { - if (Time) { - sys::TimeValue now = sys::TimeValue::now(); - int ret = ExecuteProgram(Command_, Args_); - sys::TimeValue now2 = sys::TimeValue::now(); - now2 -= now; - double elapsed = now2.seconds() + now2.microseconds() / 1000000.0; - AppendToGlobalTimeLog(Command_, elapsed); - - return ret; - } - else { - return ExecuteProgram(Command_, Args_); - } - } - - return 0; -} diff --git a/lib/CompilerDriver/BuiltinOptions.cpp b/lib/CompilerDriver/BuiltinOptions.cpp deleted file mode 100644 index 38442038d73..00000000000 --- a/lib/CompilerDriver/BuiltinOptions.cpp +++ /dev/null @@ -1,61 +0,0 @@ -//===--- BuiltinOptions.cpp - The LLVM Compiler Driver ----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Definitions of all global command-line option variables. -// -//===----------------------------------------------------------------------===// - -#include "llvm/CompilerDriver/BuiltinOptions.h" - -#ifdef ENABLE_LLVMC_DYNAMIC_PLUGINS -#include "llvm/Support/PluginLoader.h" -#endif - -namespace cl = llvm::cl; - -namespace llvmc { - -cl::list InputFilenames(cl::Positional, cl::desc(""), - cl::ZeroOrMore); -cl::opt OutputFilename("o", cl::desc("Output file name"), - cl::value_desc("file"), cl::Prefix); -cl::opt TempDirname("temp-dir", cl::desc("Temp dir name"), - cl::value_desc(""), cl::Prefix); -cl::list Languages("x", - cl::desc("Specify the language of the following input files"), - cl::ZeroOrMore); - -cl::opt DryRun("dry-run", - cl::desc("Only pretend to run commands")); -cl::opt Time("time", cl::desc("Time individual commands")); -cl::opt VerboseMode("v", - cl::desc("Enable verbose mode")); - -cl::opt CheckGraph("check-graph", - cl::desc("Check the compilation graph for errors"), - cl::Hidden); -cl::opt WriteGraph("write-graph", - cl::desc("Write compilation-graph.dot file"), - cl::Hidden); -cl::opt ViewGraph("view-graph", - cl::desc("Show compilation graph in GhostView"), - cl::Hidden); - -cl::opt SaveTemps -("save-temps", cl::desc("Keep temporary files"), - cl::init(SaveTempsEnum::Unset), - cl::values(clEnumValN(SaveTempsEnum::Obj, "obj", - "Save files in the directory specified with -o"), - clEnumValN(SaveTempsEnum::Cwd, "cwd", - "Use current working directory"), - clEnumValN(SaveTempsEnum::Obj, "", "Same as 'cwd'"), - clEnumValEnd), - cl::ValueOptional); - -} // End namespace llvmc. diff --git a/lib/CompilerDriver/CMakeLists.txt b/lib/CompilerDriver/CMakeLists.txt deleted file mode 100644 index a12b3378aaf..00000000000 --- a/lib/CompilerDriver/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -set(LLVM_LINK_COMPONENTS support) - -# We don't want this library to appear in `llvm-config --libs` output, -# so its name doesn't start with "LLVM". - -add_llvm_library(CompilerDriver - Action.cpp - BuiltinOptions.cpp - CompilationGraph.cpp - Main.cpp - Tool.cpp - ) diff --git a/lib/CompilerDriver/CompilationGraph.cpp b/lib/CompilerDriver/CompilationGraph.cpp deleted file mode 100644 index 33c6566499b..00000000000 --- a/lib/CompilerDriver/CompilationGraph.cpp +++ /dev/null @@ -1,655 +0,0 @@ -//===--- CompilationGraph.cpp - The LLVM Compiler Driver --------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Compilation graph - implementation. -// -//===----------------------------------------------------------------------===// - -#include "llvm/CompilerDriver/BuiltinOptions.h" -#include "llvm/CompilerDriver/CompilationGraph.h" -#include "llvm/CompilerDriver/Error.h" - -#include "llvm/ADT/STLExtras.h" -#include "llvm/Support/DOTGraphTraits.h" -#include "llvm/Support/GraphWriter.h" -#include "llvm/Support/raw_ostream.h" - -#include -#include -#include -#include -#include - -using namespace llvm; -using namespace llvmc; - -namespace llvmc { - - const std::string* LanguageMap::GetLanguage(const sys::Path& File) const { - // Remove the '.'. - StringRef suf = sys::path::extension(File.str()).substr(1); - LanguageMap::const_iterator Lang = - this->find(suf.empty() ? "*empty*" : suf); - if (Lang == this->end()) { - PrintError("File '" + File.str() + "' has unknown suffix '" - + suf.str() + '\''); - return 0; - } - return &Lang->second; - } -} - -namespace { - - /// ChooseEdge - Return the edge with the maximum weight. Returns 0 on error. - template - const Edge* ChooseEdge(const C& EdgesContainer, - const InputLanguagesSet& InLangs, - const std::string& NodeName = "root") { - const Edge* MaxEdge = 0; - int MaxWeight = 0; - bool SingleMax = true; - - // TODO: fix calculation of SingleMax. - for (typename C::const_iterator B = EdgesContainer.begin(), - E = EdgesContainer.end(); B != E; ++B) { - const Edge* e = B->getPtr(); - int EW = e->Weight(InLangs); - if (EW < 0) { - // (error) invocation in TableGen -> we don't need to print an error - // message. - return 0; - } - if (EW > MaxWeight) { - MaxEdge = e; - MaxWeight = EW; - SingleMax = true; - } else if (EW == MaxWeight) { - SingleMax = false; - } - } - - if (!SingleMax) { - PrintError("Node " + NodeName + ": multiple maximal outward edges found!" - " Most probably a specification error."); - return 0; - } - if (!MaxEdge) { - PrintError("Node " + NodeName + ": no maximal outward edge found!" - " Most probably a specification error."); - return 0; - } - return MaxEdge; - } - -} - -void Node::AddEdge(Edge* Edg) { - // If there already was an edge between two nodes, modify it instead - // of adding a new edge. - const std::string& ToolName = Edg->ToolName(); - for (container_type::iterator B = OutEdges.begin(), E = OutEdges.end(); - B != E; ++B) { - if ((*B)->ToolName() == ToolName) { - llvm::IntrusiveRefCntPtr(Edg).swap(*B); - return; - } - } - OutEdges.push_back(llvm::IntrusiveRefCntPtr(Edg)); -} - -CompilationGraph::CompilationGraph() { - NodesMap["root"] = Node(this); -} - -Node* CompilationGraph::getNode(const std::string& ToolName) { - nodes_map_type::iterator I = NodesMap.find(ToolName); - if (I == NodesMap.end()) { - PrintError("Node " + ToolName + " is not in the graph"); - return 0; - } - return &I->second; -} - -const Node* CompilationGraph::getNode(const std::string& ToolName) const { - nodes_map_type::const_iterator I = NodesMap.find(ToolName); - if (I == NodesMap.end()) { - PrintError("Node " + ToolName + " is not in the graph!"); - return 0; - } - return &I->second; -} - -// Find the tools list corresponding to the given language name. -const CompilationGraph::tools_vector_type* -CompilationGraph::getToolsVector(const std::string& LangName) const -{ - tools_map_type::const_iterator I = ToolsMap.find(LangName); - if (I == ToolsMap.end()) { - PrintError("No tool corresponding to the language " + LangName + " found"); - return 0; - } - return &I->second; -} - -void CompilationGraph::insertNode(Tool* V) { - if (NodesMap.count(V->Name()) == 0) - NodesMap[V->Name()] = Node(this, V); -} - -int CompilationGraph::insertEdge(const std::string& A, Edge* Edg) { - Node* B = getNode(Edg->ToolName()); - if (B == 0) - return 1; - - if (A == "root") { - const char** InLangs = B->ToolPtr->InputLanguages(); - for (;*InLangs; ++InLangs) - ToolsMap[*InLangs].push_back(IntrusiveRefCntPtr(Edg)); - NodesMap["root"].AddEdge(Edg); - } - else { - Node* N = getNode(A); - if (N == 0) - return 1; - - N->AddEdge(Edg); - } - // Increase the inward edge counter. - B->IncrInEdges(); - - return 0; -} - -// Pass input file through the chain until we bump into a Join node or -// a node that says that it is the last. -int CompilationGraph::PassThroughGraph (const sys::Path& InFile, - const Node* StartNode, - const InputLanguagesSet& InLangs, - const sys::Path& TempDir, - const LanguageMap& LangMap) const { - sys::Path In = InFile; - const Node* CurNode = StartNode; - - while(true) { - Tool* CurTool = CurNode->ToolPtr.getPtr(); - - if (CurTool->IsJoin()) { - JoinTool& JT = static_cast(*CurTool); - JT.AddToJoinList(In); - break; - } - - Action CurAction; - if (int ret = CurTool->GenerateAction(CurAction, In, CurNode->HasChildren(), - TempDir, InLangs, LangMap)) { - return ret; - } - - if (int ret = CurAction.Execute()) - return ret; - - if (CurAction.StopCompilation()) - return 0; - - const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name()); - if (Edg == 0) - return 1; - - CurNode = getNode(Edg->ToolName()); - if (CurNode == 0) - return 1; - - In = CurAction.OutFile(); - } - - return 0; -} - -// Find the head of the toolchain corresponding to the given file. -// Also, insert an input language into InLangs. -const Node* CompilationGraph:: -FindToolChain(const sys::Path& In, const std::string* ForceLanguage, - InputLanguagesSet& InLangs, const LanguageMap& LangMap) const { - - // Determine the input language. - const std::string* InLang = (ForceLanguage ? ForceLanguage - : LangMap.GetLanguage(In)); - if (InLang == 0) - return 0; - const std::string& InLanguage = *InLang; - - // Add the current input language to the input language set. - InLangs.insert(InLanguage); - - // Find the toolchain for the input language. - const tools_vector_type* pTV = getToolsVector(InLanguage); - if (pTV == 0) - return 0; - - const tools_vector_type& TV = *pTV; - if (TV.empty()) { - PrintError("No toolchain corresponding to language " - + InLanguage + " found"); - return 0; - } - - const Edge* Edg = ChooseEdge(TV, InLangs); - if (Edg == 0) - return 0; - - return getNode(Edg->ToolName()); -} - -// Helper function used by Build(). -// Traverses initial portions of the toolchains (up to the first Join node). -// This function is also responsible for handling the -x option. -int CompilationGraph::BuildInitial (InputLanguagesSet& InLangs, - const sys::Path& TempDir, - const LanguageMap& LangMap) { - // This is related to -x option handling. - cl::list::const_iterator xIter = Languages.begin(), - xBegin = xIter, xEnd = Languages.end(); - bool xEmpty = true; - const std::string* xLanguage = 0; - unsigned xPos = 0, xPosNext = 0, filePos = 0; - - if (xIter != xEnd) { - xEmpty = false; - xPos = Languages.getPosition(xIter - xBegin); - cl::list::const_iterator xNext = llvm::next(xIter); - xPosNext = (xNext == xEnd) ? std::numeric_limits::max() - : Languages.getPosition(xNext - xBegin); - xLanguage = (*xIter == "none") ? 0 : &(*xIter); - } - - // For each input file: - for (cl::list::const_iterator B = InputFilenames.begin(), - CB = B, E = InputFilenames.end(); B != E; ++B) { - sys::Path In = sys::Path(*B); - - // Code for handling the -x option. - // Output: std::string* xLanguage (can be NULL). - if (!xEmpty) { - filePos = InputFilenames.getPosition(B - CB); - - if (xPos < filePos) { - if (filePos < xPosNext) { - xLanguage = (*xIter == "none") ? 0 : &(*xIter); - } - else { // filePos >= xPosNext - // Skip xIters while filePos > xPosNext - while (filePos > xPosNext) { - ++xIter; - xPos = xPosNext; - - cl::list::const_iterator xNext = llvm::next(xIter); - if (xNext == xEnd) - xPosNext = std::numeric_limits::max(); - else - xPosNext = Languages.getPosition(xNext - xBegin); - xLanguage = (*xIter == "none") ? 0 : &(*xIter); - } - } - } - } - - // Find the toolchain corresponding to this file. - const Node* N = FindToolChain(In, xLanguage, InLangs, LangMap); - if (N == 0) - return 1; - // Pass file through the chain starting at head. - if (int ret = PassThroughGraph(In, N, InLangs, TempDir, LangMap)) - return ret; - } - - return 0; -} - -// Sort the nodes in topological order. -int CompilationGraph::TopologicalSort(std::vector& Out) { - std::queue Q; - - Node* Root = getNode("root"); - if (Root == 0) - return 1; - - Q.push(Root); - - while (!Q.empty()) { - const Node* A = Q.front(); - Q.pop(); - Out.push_back(A); - for (Node::const_iterator EB = A->EdgesBegin(), EE = A->EdgesEnd(); - EB != EE; ++EB) { - Node* B = getNode((*EB)->ToolName()); - if (B == 0) - return 1; - - B->DecrInEdges(); - if (B->HasNoInEdges()) - Q.push(B); - } - } - - return 0; -} - -namespace { - bool NotJoinNode(const Node* N) { - return N->ToolPtr ? !N->ToolPtr->IsJoin() : true; - } -} - -// Call TopologicalSort and filter the resulting list to include -// only Join nodes. -int CompilationGraph:: -TopologicalSortFilterJoinNodes(std::vector& Out) { - std::vector TopSorted; - if (int ret = TopologicalSort(TopSorted)) - return ret; - std::remove_copy_if(TopSorted.begin(), TopSorted.end(), - std::back_inserter(Out), NotJoinNode); - - return 0; -} - -int CompilationGraph::Build (const sys::Path& TempDir, - const LanguageMap& LangMap) { - InputLanguagesSet InLangs; - bool WasSomeActionGenerated = !InputFilenames.empty(); - - // Traverse initial parts of the toolchains and fill in InLangs. - if (int ret = BuildInitial(InLangs, TempDir, LangMap)) - return ret; - - std::vector JTV; - if (int ret = TopologicalSortFilterJoinNodes(JTV)) - return ret; - - // For all join nodes in topological order: - for (std::vector::iterator B = JTV.begin(), E = JTV.end(); - B != E; ++B) { - - const Node* CurNode = *B; - JoinTool* JT = &static_cast(*CurNode->ToolPtr.getPtr()); - - // Are there any files in the join list? - if (JT->JoinListEmpty() && !(JT->WorksOnEmpty() && InputFilenames.empty())) - continue; - - WasSomeActionGenerated = true; - Action CurAction; - if (int ret = JT->GenerateAction(CurAction, CurNode->HasChildren(), - TempDir, InLangs, LangMap)) { - return ret; - } - - if (int ret = CurAction.Execute()) - return ret; - - if (CurAction.StopCompilation()) - return 0; - - const Edge* Edg = ChooseEdge(CurNode->OutEdges, InLangs, CurNode->Name()); - if (Edg == 0) - return 1; - - const Node* NextNode = getNode(Edg->ToolName()); - if (NextNode == 0) - return 1; - - if (int ret = PassThroughGraph(sys::Path(CurAction.OutFile()), NextNode, - InLangs, TempDir, LangMap)) { - return ret; - } - } - - if (!WasSomeActionGenerated) { - PrintError("no input files"); - return 1; - } - - return 0; -} - -int CompilationGraph::CheckLanguageNames() const { - int ret = 0; - - // Check that names for output and input languages on all edges do match. - for (const_nodes_iterator B = this->NodesMap.begin(), - E = this->NodesMap.end(); B != E; ++B) { - - const Node & N1 = B->second; - if (N1.ToolPtr) { - for (Node::const_iterator EB = N1.EdgesBegin(), EE = N1.EdgesEnd(); - EB != EE; ++EB) { - const Node* N2 = this->getNode((*EB)->ToolName()); - if (N2 == 0) - return 1; - - if (!N2->ToolPtr) { - ++ret; - errs() << "Error: there is an edge from '" << N1.ToolPtr->Name() - << "' back to the root!\n\n"; - continue; - } - - const char** OutLangs = N1.ToolPtr->OutputLanguages(); - const char** InLangs = N2->ToolPtr->InputLanguages(); - bool eq = false; - const char* OutLang = 0; - for (;*OutLangs; ++OutLangs) { - OutLang = *OutLangs; - for (;*InLangs; ++InLangs) { - if (std::strcmp(OutLang, *InLangs) == 0) { - eq = true; - break; - } - } - } - - if (!eq) { - ++ret; - errs() << "Error: Output->input language mismatch in the edge '" - << N1.ToolPtr->Name() << "' -> '" << N2->ToolPtr->Name() - << "'!\n" - << "Expected one of { "; - - InLangs = N2->ToolPtr->InputLanguages(); - for (;*InLangs; ++InLangs) { - errs() << '\'' << *InLangs << (*(InLangs+1) ? "', " : "'"); - } - - errs() << " }, but got '" << OutLang << "'!\n\n"; - } - - } - } - } - - return ret; -} - -int CompilationGraph::CheckMultipleDefaultEdges() const { - int ret = 0; - InputLanguagesSet Dummy; - - // For all nodes, just iterate over the outgoing edges and check if there is - // more than one edge with maximum weight. - for (const_nodes_iterator B = this->NodesMap.begin(), - E = this->NodesMap.end(); B != E; ++B) { - const Node& N = B->second; - int MaxWeight = -1024; - - // Ignore the root node. - if (!N.ToolPtr) - continue; - - for (Node::const_iterator EB = N.EdgesBegin(), EE = N.EdgesEnd(); - EB != EE; ++EB) { - int EdgeWeight = (*EB)->Weight(Dummy); - if (EdgeWeight > MaxWeight) { - MaxWeight = EdgeWeight; - } - else if (EdgeWeight == MaxWeight) { - ++ret; - errs() << "Error: there are multiple maximal edges stemming from the '" - << N.ToolPtr->Name() << "' node!\n\n"; - break; - } - } - } - - return ret; -} - -int CompilationGraph::CheckCycles() { - unsigned deleted = 0; - std::queue Q; - - Node* Root = getNode("root"); - if (Root == 0) - return 1; - - Q.push(Root); - - // Try to delete all nodes that have no ingoing edges, starting from the - // root. If there are any nodes left after this operation, then we have a - // cycle. This relies on '--check-graph' not performing the topological sort. - while (!Q.empty()) { - Node* A = Q.front(); - Q.pop(); - ++deleted; - - for (Node::iterator EB = A->EdgesBegin(), EE = A->EdgesEnd(); - EB != EE; ++EB) { - Node* B = getNode((*EB)->ToolName()); - if (B == 0) - return 1; - - B->DecrInEdges(); - if (B->HasNoInEdges()) - Q.push(B); - } - } - - if (deleted != NodesMap.size()) { - errs() << "Error: there are cycles in the compilation graph!\n" - << "Try inspecting the diagram produced by " - << "'llvmc --view-graph'.\n\n"; - return 1; - } - - return 0; -} - -int CompilationGraph::Check () { - // We try to catch as many errors as we can in one go. - int errs = 0; - int ret = 0; - - // Check that output/input language names match. - ret = this->CheckLanguageNames(); - if (ret < 0) - return 1; - errs += ret; - - // Check for multiple default edges. - ret = this->CheckMultipleDefaultEdges(); - if (ret < 0) - return 1; - errs += ret; - - // Check for cycles. - ret = this->CheckCycles(); - if (ret < 0) - return 1; - errs += ret; - - return errs; -} - -// Code related to graph visualization. - -namespace { - -std::string SquashStrArray (const char** StrArr) { - std::string ret; - - for (; *StrArr; ++StrArr) { - if (*(StrArr + 1)) { - ret += *StrArr; - ret += ", "; - } - else { - ret += *StrArr; - } - } - - return ret; -} - -} // End anonymous namespace. - -namespace llvm { - template <> - struct DOTGraphTraits - : public DefaultDOTGraphTraits - { - DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} - - template - static std::string getNodeLabel(const Node* N, const GraphType&) - { - if (N->ToolPtr) - if (N->ToolPtr->IsJoin()) - return N->Name() + "\n (join" + - (N->HasChildren() ? ")" - : std::string(": ") + - SquashStrArray(N->ToolPtr->OutputLanguages()) + ')'); - else - return N->Name(); - else - return "root"; - } - - template - static std::string getEdgeSourceLabel(const Node* N, EdgeIter I) { - if (N->ToolPtr) { - return SquashStrArray(N->ToolPtr->OutputLanguages()); - } - else { - return SquashStrArray(I->ToolPtr->InputLanguages()); - } - } - }; - -} // End namespace llvm - -int CompilationGraph::writeGraph(const std::string& OutputFilename) { - std::string ErrorInfo; - raw_fd_ostream O(OutputFilename.c_str(), ErrorInfo); - - if (ErrorInfo.empty()) { - errs() << "Writing '"<< OutputFilename << "' file..."; - llvm::WriteGraph(O, this); - errs() << "done.\n"; - } - else { - PrintError("Error opening file '" + OutputFilename + "' for writing!"); - return 1; - } - - return 0; -} - -void CompilationGraph::viewGraph() { - llvm::ViewGraph(this, "compilation-graph"); -} diff --git a/lib/CompilerDriver/Main.cpp b/lib/CompilerDriver/Main.cpp deleted file mode 100644 index 7120027f7ce..00000000000 --- a/lib/CompilerDriver/Main.cpp +++ /dev/null @@ -1,146 +0,0 @@ -//===--- Main.cpp - The LLVM Compiler Driver --------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// llvmc::Main function - driver entry point. -// -//===----------------------------------------------------------------------===// - -#include "llvm/CompilerDriver/AutoGenerated.h" -#include "llvm/CompilerDriver/BuiltinOptions.h" -#include "llvm/CompilerDriver/CompilationGraph.h" -#include "llvm/CompilerDriver/Error.h" - -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/Support/Path.h" - -#include -#include - -namespace cl = llvm::cl; -namespace sys = llvm::sys; -using namespace llvmc; - -namespace { - - std::stringstream* GlobalTimeLog; - - /// GetTempDir - Get the temporary directory location. Returns non-zero value - /// on error. - int GetTempDir(sys::Path& tempDir) { - // The --temp-dir option. - if (!TempDirname.empty()) { - tempDir = TempDirname; - } - // GCC 4.5-style -save-temps handling. - else if (SaveTemps == SaveTempsEnum::Unset) { - tempDir = sys::Path::GetTemporaryDirectory(); - return 0; - } - else if (SaveTemps == SaveTempsEnum::Obj && !OutputFilename.empty()) { - tempDir = sys::path::parent_path(OutputFilename); - } - else { - // SaveTemps == Cwd --> use current dir (leave tempDir empty). - return 0; - } - - bool Exists; - if (llvm::sys::fs::exists(tempDir.str(), Exists) || !Exists) { - std::string ErrMsg; - if (tempDir.createDirectoryOnDisk(true, &ErrMsg)) { - PrintError(ErrMsg); - return 1; - } - } - - return 0; - } - - /// BuildTargets - A small wrapper for CompilationGraph::Build. Returns - /// non-zero value in case of error. - int BuildTargets(CompilationGraph& graph, const LanguageMap& langMap) { - int ret; - sys::Path tempDir; - bool toDelete = (SaveTemps == SaveTempsEnum::Unset); - - if (int ret = GetTempDir(tempDir)) - return ret; - - ret = graph.Build(tempDir, langMap); - - if (toDelete) - tempDir.eraseFromDisk(true); - - return ret; - } -} - -namespace llvmc { - -// Used to implement -time option. External linkage is intentional. -void AppendToGlobalTimeLog(const std::string& cmd, double time) { - *GlobalTimeLog << "# " << cmd << ' ' << time << '\n'; -} - -// Sometimes user code wants to access the argv[0] value. -const char* ProgramName; - -int Main(int argc, char** argv) { - int ret = 0; - LanguageMap langMap; - CompilationGraph graph; - - ProgramName = argv[0]; - - cl::ParseCommandLineOptions - (argc, argv, - /* Overview = */ "LLVM Compiler Driver (Work In Progress)", - /* ReadResponseFiles = */ false); - - if (int ret = autogenerated::RunInitialization(langMap, graph)) - return ret; - - if (CheckGraph) { - ret = graph.Check(); - if (!ret) - llvm::errs() << "check-graph: no errors found.\n"; - - return ret; - } - - if (ViewGraph) { - graph.viewGraph(); - if (!WriteGraph) - return 0; - } - - if (WriteGraph) { - const std::string& Out = (OutputFilename.empty() - ? std::string("compilation-graph.dot") - : OutputFilename); - return graph.writeGraph(Out); - } - - if (Time) { - GlobalTimeLog = new std::stringstream; - GlobalTimeLog->precision(2); - } - - ret = BuildTargets(graph, langMap); - - if (Time) { - llvm::errs() << GlobalTimeLog->str(); - delete GlobalTimeLog; - } - - return ret; -} - -} // end namespace llvmc diff --git a/lib/CompilerDriver/Makefile b/lib/CompilerDriver/Makefile deleted file mode 100644 index 10cfa4f0292..00000000000 --- a/lib/CompilerDriver/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -##===- lib/CompilerDriver/Makefile -------------------------*- Makefile -*-===## -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open -# Source License. See LICENSE.TXT for details. -# -##===----------------------------------------------------------------------===## - -LEVEL = ../.. - -# We don't want this library to appear in `llvm-config --libs` output, so its -# name doesn't start with "LLVM" and NO_LLVM_CONFIG is set. - -LIBRARYNAME = CompilerDriver -LINK_COMPONENTS = support -NO_LLVM_CONFIG = 1 - - -include $(LEVEL)/Makefile.common diff --git a/lib/CompilerDriver/Tool.cpp b/lib/CompilerDriver/Tool.cpp deleted file mode 100644 index 876759aa72b..00000000000 --- a/lib/CompilerDriver/Tool.cpp +++ /dev/null @@ -1,95 +0,0 @@ -//===--- Tool.cpp - The LLVM Compiler Driver --------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// Tool base class - implementation details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/CompilerDriver/BuiltinOptions.h" -#include "llvm/CompilerDriver/Tool.h" - -#include "llvm/ADT/StringExtras.h" -#include "llvm/Support/Path.h" - -#include - -using namespace llvm; -using namespace llvmc; - -namespace { - sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName, - const std::string& Suffix) { - sys::Path Out; - - // Make sure we don't end up with path names like '/file.o' if the - // TempDir is empty. - if (TempDir.empty()) { - Out.set(BaseName); - } - else { - Out = TempDir; - Out.appendComponent(BaseName); - } - Out.appendSuffix(Suffix); - // NOTE: makeUnique always *creates* a unique temporary file, - // which is good, since there will be no races. However, some - // tools do not like it when the output file already exists, so - // they need to be placated with -f or something like that. - Out.makeUnique(true, NULL); - return Out; - } -} - -sys::Path Tool::OutFilename(const sys::Path& In, - const sys::Path& TempDir, - bool StopCompilation, - const char* OutputSuffix) const { - sys::Path Out; - - if (StopCompilation) { - if (!OutputFilename.empty()) { - Out.set(OutputFilename); - } - else if (IsJoin()) { - Out.set("a"); - Out.appendSuffix(OutputSuffix); - } - else { - Out.set(sys::path::stem(In.str())); - Out.appendSuffix(OutputSuffix); - } - } - else { - if (IsJoin()) - Out = MakeTempFile(TempDir, "tmp", OutputSuffix); - else - Out = MakeTempFile(TempDir, sys::path::stem(In.str()), OutputSuffix); - } - return Out; -} - -namespace { - template - bool CompareFirst (std::pair p1, std::pair p2) { - return std::less()(p1.first, p2.first); - } -} - -StrVector Tool::SortArgs(ArgsVector& Args) const { - StrVector Out; - - // HACK: this won't be needed when we'll migrate away from CommandLine. - std::stable_sort(Args.begin(), Args.end(), - &CompareFirst); - for (ArgsVector::iterator B = Args.begin(), E = Args.end(); B != E; ++B) { - Out.push_back(B->second); - } - - return Out; -} diff --git a/lib/Makefile b/lib/Makefile index 1752bde35ac..fd575cd1957 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -11,7 +11,7 @@ LEVEL = .. include $(LEVEL)/Makefile.config PARALLEL_DIRS := VMCore AsmParser Bitcode Archive Analysis Transforms CodeGen \ - Target ExecutionEngine Linker MC CompilerDriver Object DebugInfo + Target ExecutionEngine Linker MC Object DebugInfo include $(LEVEL)/Makefile.common diff --git a/utils/TableGen/CMakeLists.txt b/utils/TableGen/CMakeLists.txt index 047d731de6b..0202f53c427 100644 --- a/utils/TableGen/CMakeLists.txt +++ b/utils/TableGen/CMakeLists.txt @@ -31,7 +31,6 @@ add_llvm_utility(tblgen InstrEnumEmitter.cpp InstrInfoEmitter.cpp IntrinsicEmitter.cpp - LLVMCConfigurationEmitter.cpp NeonEmitter.cpp OptParserEmitter.cpp PseudoLoweringEmitter.cpp diff --git a/utils/TableGen/LLVMCConfigurationEmitter.cpp b/utils/TableGen/LLVMCConfigurationEmitter.cpp deleted file mode 100644 index cd0cbeb1c6b..00000000000 --- a/utils/TableGen/LLVMCConfigurationEmitter.cpp +++ /dev/null @@ -1,3134 +0,0 @@ -//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This tablegen backend is responsible for emitting LLVMC configuration code. -// -//===----------------------------------------------------------------------===// - -#include "LLVMCConfigurationEmitter.h" -#include "Record.h" - -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/StringSet.h" - -#include -#include -#include -#include -#include -#include - - -using namespace llvm; - -namespace { - -//===----------------------------------------------------------------------===// -/// Typedefs - -typedef std::vector RecordVector; -typedef std::vector DagVector; -typedef std::vector StrVector; - -//===----------------------------------------------------------------------===// -/// Constants - -// Indentation. -const unsigned TabWidth = 4; -const unsigned Indent1 = TabWidth*1; -const unsigned Indent2 = TabWidth*2; -const unsigned Indent3 = TabWidth*3; -const unsigned Indent4 = TabWidth*4; - -// Default help string. -const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED"; - -// Name for the "sink" option. -const char * const SinkOptionName = "SinkOption"; - -//===----------------------------------------------------------------------===// -/// Helper functions - -/// Id - An 'identity' function object. -struct Id { - template - void operator()(const T0&) const { - } - template - void operator()(const T0&, const T1&) const { - } - template - void operator()(const T0&, const T1&, const T2&) const { - } -}; - -int InitPtrToInt(const Init* ptr) { - const IntInit& val = dynamic_cast(*ptr); - return val.getValue(); -} - -bool InitPtrToBool(const Init* ptr) { - bool ret = false; - const DefInit& val = dynamic_cast(*ptr); - const std::string& str = val.getAsString(); - - if (str == "true") { - ret = true; - } - else if (str == "false") { - ret = false; - } - else { - throw "Incorrect boolean value: '" + str + - "': must be either 'true' or 'false'"; - } - - return ret; -} - -const std::string& InitPtrToString(const Init* ptr) { - const StringInit& val = dynamic_cast(*ptr); - return val.getValue(); -} - -const ListInit& InitPtrToList(const Init* ptr) { - const ListInit& val = dynamic_cast(*ptr); - return val; -} - -const DagInit& InitPtrToDag(const Init* ptr) { - const DagInit& val = dynamic_cast(*ptr); - return val; -} - -const std::string GetOperatorName(const DagInit& D) { - return D.getOperator()->getAsString(); -} - -/// CheckBooleanConstant - Check that the provided value is a boolean constant. -void CheckBooleanConstant(const Init* I) { - InitPtrToBool(I); -} - -// CheckNumberOfArguments - Ensure that the number of args in d is -// greater than or equal to min_arguments, otherwise throw an exception. -void CheckNumberOfArguments (const DagInit& d, unsigned minArgs) { - if (d.getNumArgs() < minArgs) - throw GetOperatorName(d) + ": too few arguments!"; -} - -// EscapeVariableName - Escape commas and other symbols not allowed -// in the C++ variable names. Makes it possible to use options named -// like "Wa," (useful for prefix options). -std::string EscapeVariableName (const std::string& Var) { - std::string ret; - for (unsigned i = 0; i != Var.size(); ++i) { - char cur_char = Var[i]; - if (cur_char == ',') { - ret += "_comma_"; - } - else if (cur_char == '+') { - ret += "_plus_"; - } - else if (cur_char == '-') { - ret += "_dash_"; - } - else { - ret.push_back(cur_char); - } - } - return ret; -} - -/// EscapeQuotes - Replace '"' with '\"'. -std::string EscapeQuotes (const std::string& Var) { - std::string ret; - for (unsigned i = 0; i != Var.size(); ++i) { - char cur_char = Var[i]; - if (cur_char == '"') { - ret += "\\\""; - } - else { - ret.push_back(cur_char); - } - } - return ret; -} - -/// OneOf - Does the input string contain this character? -bool OneOf(const char* lst, char c) { - while (*lst) { - if (*lst++ == c) - return true; - } - return false; -} - -template -void CheckedIncrement(I& P, I E, S ErrorString) { - ++P; - if (P == E) - throw ErrorString; -} - -//===----------------------------------------------------------------------===// -/// Back-end specific code - - -/// OptionType - One of six different option types. See the -/// documentation for detailed description of differences. -namespace OptionType { - - enum OptionType { Alias, Switch, SwitchList, - Parameter, ParameterList, Prefix, PrefixList }; - - bool IsAlias(OptionType t) { - return (t == Alias); - } - - bool IsList (OptionType t) { - return (t == SwitchList || t == ParameterList || t == PrefixList); - } - - bool IsSwitch (OptionType t) { - return (t == Switch); - } - - bool IsSwitchList (OptionType t) { - return (t == SwitchList); - } - - bool IsParameter (OptionType t) { - return (t == Parameter || t == Prefix); - } - -} - -OptionType::OptionType stringToOptionType(const std::string& T) { - if (T == "alias_option") - return OptionType::Alias; - else if (T == "switch_option") - return OptionType::Switch; - else if (T == "switch_list_option") - return OptionType::SwitchList; - else if (T == "parameter_option") - return OptionType::Parameter; - else if (T == "parameter_list_option") - return OptionType::ParameterList; - else if (T == "prefix_option") - return OptionType::Prefix; - else if (T == "prefix_list_option") - return OptionType::PrefixList; - else - throw "Unknown option type: " + T + '!'; -} - -namespace OptionDescriptionFlags { - enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2, - ReallyHidden = 0x4, OneOrMore = 0x8, - Optional = 0x10, CommaSeparated = 0x20, - ForwardNotSplit = 0x40, ZeroOrMore = 0x80 }; -} - -/// OptionDescription - Represents data contained in a single -/// OptionList entry. -struct OptionDescription { - OptionType::OptionType Type; - std::string Name; - unsigned Flags; - std::string Help; - unsigned MultiVal; - Init* InitVal; - - OptionDescription(OptionType::OptionType t = OptionType::Switch, - const std::string& n = "", - const std::string& h = DefaultHelpString) - : Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0) - {} - - /// GenTypeDeclaration - Returns the C++ variable type of this - /// option. - const char* GenTypeDeclaration() const; - - /// GenVariableName - Returns the variable name used in the - /// generated C++ code. - std::string GenVariableName() const - { return "autogenerated::" + GenOptionType() + EscapeVariableName(Name); } - - /// GenPlainVariableName - Returns the variable name without the namespace - /// prefix. - std::string GenPlainVariableName() const - { return GenOptionType() + EscapeVariableName(Name); } - - /// Merge - Merge two option descriptions. - void Merge (const OptionDescription& other); - - /// CheckConsistency - Check that the flags are consistent. - void CheckConsistency() const; - - // Misc convenient getters/setters. - - bool isAlias() const; - - bool isMultiVal() const; - - bool isCommaSeparated() const; - void setCommaSeparated(); - - bool isForwardNotSplit() const; - void setForwardNotSplit(); - - bool isRequired() const; - void setRequired(); - - bool isOneOrMore() const; - void setOneOrMore(); - - bool isZeroOrMore() const; - void setZeroOrMore(); - - bool isOptional() const; - void setOptional(); - - bool isHidden() const; - void setHidden(); - - bool isReallyHidden() const; - void setReallyHidden(); - - bool isSwitch() const - { return OptionType::IsSwitch(this->Type); } - - bool isSwitchList() const - { return OptionType::IsSwitchList(this->Type); } - - bool isParameter() const - { return OptionType::IsParameter(this->Type); } - - bool isList() const - { return OptionType::IsList(this->Type); } - - bool isParameterList() const - { return (OptionType::IsList(this->Type) - && !OptionType::IsSwitchList(this->Type)); } - -private: - - // GenOptionType - Helper function used by GenVariableName(). - std::string GenOptionType() const; -}; - -void OptionDescription::CheckConsistency() const { - unsigned i = 0; - - i += this->isRequired(); - i += this->isOptional(); - i += this->isOneOrMore(); - i += this->isZeroOrMore(); - - if (i > 1) { - throw "Only one of (required), (optional), (one_or_more) or " - "(zero_or_more) properties is allowed!"; - } -} - -void OptionDescription::Merge (const OptionDescription& other) -{ - if (other.Type != Type) - throw "Conflicting definitions for the option " + Name + "!"; - - if (Help == other.Help || Help == DefaultHelpString) - Help = other.Help; - else if (other.Help != DefaultHelpString) { - llvm::errs() << "Warning: several different help strings" - " defined for option " + Name + "\n"; - } - - Flags |= other.Flags; -} - -bool OptionDescription::isAlias() const { - return OptionType::IsAlias(this->Type); -} - -bool OptionDescription::isMultiVal() const { - return MultiVal > 1; -} - -bool OptionDescription::isCommaSeparated() const { - return Flags & OptionDescriptionFlags::CommaSeparated; -} -void OptionDescription::setCommaSeparated() { - Flags |= OptionDescriptionFlags::CommaSeparated; -} - -bool OptionDescription::isForwardNotSplit() const { - return Flags & OptionDescriptionFlags::ForwardNotSplit; -} -void OptionDescription::setForwardNotSplit() { - Flags |= OptionDescriptionFlags::ForwardNotSplit; -} - -bool OptionDescription::isRequired() const { - return Flags & OptionDescriptionFlags::Required; -} -void OptionDescription::setRequired() { - Flags |= OptionDescriptionFlags::Required; -} - -bool OptionDescription::isOneOrMore() const { - return Flags & OptionDescriptionFlags::OneOrMore; -} -void OptionDescription::setOneOrMore() { - Flags |= OptionDescriptionFlags::OneOrMore; -} - -bool OptionDescription::isZeroOrMore() const { - return Flags & OptionDescriptionFlags::ZeroOrMore; -} -void OptionDescription::setZeroOrMore() { - Flags |= OptionDescriptionFlags::ZeroOrMore; -} - -bool OptionDescription::isOptional() const { - return Flags & OptionDescriptionFlags::Optional; -} -void OptionDescription::setOptional() { - Flags |= OptionDescriptionFlags::Optional; -} - -bool OptionDescription::isHidden() const { - return Flags & OptionDescriptionFlags::Hidden; -} -void OptionDescription::setHidden() { - Flags |= OptionDescriptionFlags::Hidden; -} - -bool OptionDescription::isReallyHidden() const { - return Flags & OptionDescriptionFlags::ReallyHidden; -} -void OptionDescription::setReallyHidden() { - Flags |= OptionDescriptionFlags::ReallyHidden; -} - -const char* OptionDescription::GenTypeDeclaration() const { - switch (Type) { - case OptionType::Alias: - return "cl::alias"; - case OptionType::PrefixList: - case OptionType::ParameterList: - return "cl::list"; - case OptionType::Switch: - return "cl::opt"; - case OptionType::SwitchList: - return "cl::list"; - case OptionType::Parameter: - case OptionType::Prefix: - default: - return "cl::opt"; - } -} - -std::string OptionDescription::GenOptionType() const { - switch (Type) { - case OptionType::Alias: - return "Alias_"; - case OptionType::PrefixList: - case OptionType::ParameterList: - return "List_"; - case OptionType::Switch: - return "Switch_"; - case OptionType::SwitchList: - return "SwitchList_"; - case OptionType::Prefix: - case OptionType::Parameter: - default: - return "Parameter_"; - } -} - -/// OptionDescriptions - An OptionDescription array plus some helper -/// functions. -class OptionDescriptions { - typedef StringMap container_type; - - /// Descriptions - A list of OptionDescriptions. - container_type Descriptions; - -public: - /// FindOption - exception-throwing wrapper for find(). - const OptionDescription& FindOption(const std::string& OptName) const; - - // Wrappers for FindOption that throw an exception in case the option has a - // wrong type. - const OptionDescription& FindSwitch(const std::string& OptName) const; - const OptionDescription& FindParameter(const std::string& OptName) const; - const OptionDescription& FindParameterList(const std::string& OptName) const; - const OptionDescription& - FindListOrParameter(const std::string& OptName) const; - const OptionDescription& - FindParameterListOrParameter(const std::string& OptName) const; - - /// insertDescription - Insert new OptionDescription into - /// OptionDescriptions list - void InsertDescription (const OptionDescription& o); - - // Support for STL-style iteration - typedef container_type::const_iterator const_iterator; - const_iterator begin() const { return Descriptions.begin(); } - const_iterator end() const { return Descriptions.end(); } -}; - -const OptionDescription& -OptionDescriptions::FindOption(const std::string& OptName) const { - const_iterator I = Descriptions.find(OptName); - if (I != Descriptions.end()) - return I->second; - else - throw OptName + ": no such option!"; -} - -const OptionDescription& -OptionDescriptions::FindSwitch(const std::string& OptName) const { - const OptionDescription& OptDesc = this->FindOption(OptName); - if (!OptDesc.isSwitch()) - throw OptName + ": incorrect option type - should be a switch!"; - return OptDesc; -} - -const OptionDescription& -OptionDescriptions::FindParameterList(const std::string& OptName) const { - const OptionDescription& OptDesc = this->FindOption(OptName); - if (!OptDesc.isList() || OptDesc.isSwitchList()) - throw OptName + ": incorrect option type - should be a parameter list!"; - return OptDesc; -} - -const OptionDescription& -OptionDescriptions::FindParameter(const std::string& OptName) const { - const OptionDescription& OptDesc = this->FindOption(OptName); - if (!OptDesc.isParameter()) - throw OptName + ": incorrect option type - should be a parameter!"; - return OptDesc; -} - -const OptionDescription& -OptionDescriptions::FindListOrParameter(const std::string& OptName) const { - const OptionDescription& OptDesc = this->FindOption(OptName); - if (!OptDesc.isList() && !OptDesc.isParameter()) - throw OptName - + ": incorrect option type - should be a list or parameter!"; - return OptDesc; -} - -const OptionDescription& -OptionDescriptions::FindParameterListOrParameter -(const std::string& OptName) const { - const OptionDescription& OptDesc = this->FindOption(OptName); - if ((!OptDesc.isList() && !OptDesc.isParameter()) || OptDesc.isSwitchList()) - throw OptName - + ": incorrect option type - should be a parameter list or parameter!"; - return OptDesc; -} - -void OptionDescriptions::InsertDescription (const OptionDescription& o) { - container_type::iterator I = Descriptions.find(o.Name); - if (I != Descriptions.end()) { - OptionDescription& D = I->second; - D.Merge(o); - } - else { - Descriptions[o.Name] = o; - } -} - -/// HandlerTable - A base class for function objects implemented as -/// 'tables of handlers'. -template -class HandlerTable { -protected: - // Implementation details. - - /// HandlerMap - A map from property names to property handlers - typedef StringMap HandlerMap; - - static HandlerMap Handlers_; - static bool staticMembersInitialized_; - -public: - - Handler GetHandler (const std::string& HandlerName) const { - typename HandlerMap::iterator method = Handlers_.find(HandlerName); - - if (method != Handlers_.end()) { - Handler h = method->second; - return h; - } - else { - throw "No handler found for property " + HandlerName + "!"; - } - } - - void AddHandler(const char* Property, Handler H) { - Handlers_[Property] = H; - } - -}; - -template -Handler GetHandler(FunctionObject* Obj, const DagInit& Dag) { - const std::string& HandlerName = GetOperatorName(Dag); - return Obj->GetHandler(HandlerName); -} - -template -void InvokeDagInitHandler(FunctionObject* Obj, Init* I) { - typedef void (FunctionObject::*Handler) (const DagInit&); - - const DagInit& Dag = InitPtrToDag(I); - Handler h = GetHandler(Obj, Dag); - - ((Obj)->*(h))(Dag); -} - -template -void InvokeDagInitHandler(const FunctionObject* const Obj, - const Init* I, unsigned IndentLevel, raw_ostream& O) -{ - typedef void (FunctionObject::*Handler) - (const DagInit&, unsigned IndentLevel, raw_ostream& O) const; - - const DagInit& Dag = InitPtrToDag(I); - Handler h = GetHandler(Obj, Dag); - - ((Obj)->*(h))(Dag, IndentLevel, O); -} - -template -typename HandlerTable::HandlerMap HandlerTable::Handlers_; - -template -bool HandlerTable::staticMembersInitialized_ = false; - - -/// CollectOptionProperties - Function object for iterating over an -/// option property list. -class CollectOptionProperties; -typedef void (CollectOptionProperties::* CollectOptionPropertiesHandler) -(const DagInit&); - -class CollectOptionProperties -: public HandlerTable -{ -private: - - /// optDescs_ - OptionDescriptions table. This is where the - /// information is stored. - OptionDescription& optDesc_; - -public: - - explicit CollectOptionProperties(OptionDescription& OD) - : optDesc_(OD) - { - if (!staticMembersInitialized_) { - AddHandler("help", &CollectOptionProperties::onHelp); - AddHandler("hidden", &CollectOptionProperties::onHidden); - AddHandler("init", &CollectOptionProperties::onInit); - AddHandler("multi_val", &CollectOptionProperties::onMultiVal); - AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore); - AddHandler("zero_or_more", &CollectOptionProperties::onZeroOrMore); - AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden); - AddHandler("required", &CollectOptionProperties::onRequired); - AddHandler("optional", &CollectOptionProperties::onOptional); - AddHandler("comma_separated", &CollectOptionProperties::onCommaSeparated); - AddHandler("forward_not_split", - &CollectOptionProperties::onForwardNotSplit); - - staticMembersInitialized_ = true; - } - } - - /// operator() - Just forwards to the corresponding property - /// handler. - void operator() (Init* I) { - InvokeDagInitHandler(this, I); - } - -private: - - /// Option property handlers -- - /// Methods that handle option properties such as (help) or (hidden). - - void onHelp (const DagInit& d) { - CheckNumberOfArguments(d, 1); - optDesc_.Help = EscapeQuotes(InitPtrToString(d.getArg(0))); - } - - void onHidden (const DagInit& d) { - CheckNumberOfArguments(d, 0); - optDesc_.setHidden(); - } - - void onReallyHidden (const DagInit& d) { - CheckNumberOfArguments(d, 0); - optDesc_.setReallyHidden(); - } - - void onCommaSeparated (const DagInit& d) { - CheckNumberOfArguments(d, 0); - if (!optDesc_.isParameterList()) - throw "'comma_separated' is valid only on parameter list options!"; - optDesc_.setCommaSeparated(); - } - - void onForwardNotSplit (const DagInit& d) { - CheckNumberOfArguments(d, 0); - if (!optDesc_.isParameter()) - throw "'forward_not_split' is valid only for parameter options!"; - optDesc_.setForwardNotSplit(); - } - - void onRequired (const DagInit& d) { - CheckNumberOfArguments(d, 0); - - optDesc_.setRequired(); - optDesc_.CheckConsistency(); - } - - void onInit (const DagInit& d) { - CheckNumberOfArguments(d, 1); - Init* i = d.getArg(0); - const std::string& str = i->getAsString(); - - bool correct = optDesc_.isParameter() && dynamic_cast(i); - correct |= (optDesc_.isSwitch() && (str == "true" || str == "false")); - - if (!correct) - throw "Incorrect usage of the 'init' option property!"; - - optDesc_.InitVal = i; - } - - void onOneOrMore (const DagInit& d) { - CheckNumberOfArguments(d, 0); - - optDesc_.setOneOrMore(); - optDesc_.CheckConsistency(); - } - - void onZeroOrMore (const DagInit& d) { - CheckNumberOfArguments(d, 0); - - if (optDesc_.isList()) - llvm::errs() << "Warning: specifying the 'zero_or_more' property " - "on a list option has no effect.\n"; - - optDesc_.setZeroOrMore(); - optDesc_.CheckConsistency(); - } - - void onOptional (const DagInit& d) { - CheckNumberOfArguments(d, 0); - - if (!optDesc_.isList()) - llvm::errs() << "Warning: specifying the 'optional' property" - "on a non-list option has no effect.\n"; - - optDesc_.setOptional(); - optDesc_.CheckConsistency(); - } - - void onMultiVal (const DagInit& d) { - CheckNumberOfArguments(d, 1); - int val = InitPtrToInt(d.getArg(0)); - if (val < 2) - throw "Error in the 'multi_val' property: " - "the value must be greater than 1!"; - if (!optDesc_.isParameterList()) - throw "The multi_val property is valid only on list options!"; - optDesc_.MultiVal = val; - } - -}; - -/// AddOption - A function object that is applied to every option -/// description. Used by CollectOptionDescriptions. -class AddOption { -private: - OptionDescriptions& OptDescs_; - -public: - explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD) - {} - - void operator()(const Init* i) { - const DagInit& d = InitPtrToDag(i); - CheckNumberOfArguments(d, 1); - - const OptionType::OptionType Type = - stringToOptionType(GetOperatorName(d)); - const std::string& Name = InitPtrToString(d.getArg(0)); - - OptionDescription OD(Type, Name); - - CheckNumberOfArguments(d, 2); - - // Alias option store the aliased option name in the 'Help' field and do not - // have any properties. - if (OD.isAlias()) { - OD.Help = InitPtrToString(d.getArg(1)); - } - else { - processOptionProperties(d, OD); - } - - // Switch options are ZeroOrMore by default. - if (OD.isSwitch()) { - if (!(OD.isOptional() || OD.isOneOrMore() || OD.isRequired())) - OD.setZeroOrMore(); - } - - OptDescs_.InsertDescription(OD); - } - -private: - /// processOptionProperties - Go through the list of option - /// properties and call a corresponding handler for each. - static void processOptionProperties (const DagInit& d, OptionDescription& o) { - CheckNumberOfArguments(d, 2); - DagInit::const_arg_iterator B = d.arg_begin(); - // Skip the first argument: it's always the option name. - ++B; - std::for_each(B, d.arg_end(), CollectOptionProperties(o)); - } - -}; - -/// CollectOptionDescriptions - Collects option properties from all -/// OptionLists. -void CollectOptionDescriptions (const RecordVector& V, - OptionDescriptions& OptDescs) -{ - // For every OptionList: - for (RecordVector::const_iterator B = V.begin(), E = V.end(); B!=E; ++B) - { - // Throws an exception if the value does not exist. - ListInit* PropList = (*B)->getValueAsListInit("options"); - - // For every option description in this list: invoke AddOption. - std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs)); - } -} - -// Tool information record - -namespace ToolFlags { - enum ToolFlags { Join = 0x1, Sink = 0x2 }; -} - -struct ToolDescription : public RefCountedBase { - std::string Name; - Init* CmdLine; - Init* Actions; - StrVector InLanguage; - std::string InFileOption; - std::string OutFileOption; - StrVector OutLanguage; - std::string OutputSuffix; - unsigned Flags; - const Init* OnEmpty; - - // Various boolean properties - void setSink() { Flags |= ToolFlags::Sink; } - bool isSink() const { return Flags & ToolFlags::Sink; } - void setJoin() { Flags |= ToolFlags::Join; } - bool isJoin() const { return Flags & ToolFlags::Join; } - - // Default ctor here is needed because StringMap can only store - // DefaultConstructible objects - ToolDescription (const std::string &n = "") - : Name(n), CmdLine(0), Actions(0), OutFileOption("-o"), - Flags(0), OnEmpty(0) - {} -}; - -/// ToolDescriptions - A list of Tool information records. -typedef std::vector > ToolDescriptions; - - -/// CollectToolProperties - Function object for iterating over a list of -/// tool property records. - -class CollectToolProperties; -typedef void (CollectToolProperties::* CollectToolPropertiesHandler) -(const DagInit&); - -class CollectToolProperties : public HandlerTable -{ -private: - - /// toolDesc_ - Properties of the current Tool. This is where the - /// information is stored. - ToolDescription& toolDesc_; - -public: - - explicit CollectToolProperties (ToolDescription& d) - : toolDesc_(d) - { - if (!staticMembersInitialized_) { - - AddHandler("actions", &CollectToolProperties::onActions); - AddHandler("command", &CollectToolProperties::onCommand); - AddHandler("in_language", &CollectToolProperties::onInLanguage); - AddHandler("join", &CollectToolProperties::onJoin); - AddHandler("out_language", &CollectToolProperties::onOutLanguage); - - AddHandler("out_file_option", &CollectToolProperties::onOutFileOption); - AddHandler("in_file_option", &CollectToolProperties::onInFileOption); - - AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix); - AddHandler("sink", &CollectToolProperties::onSink); - AddHandler("works_on_empty", &CollectToolProperties::onWorksOnEmpty); - - staticMembersInitialized_ = true; - } - } - - void operator() (Init* I) { - InvokeDagInitHandler(this, I); - } - -private: - - /// Property handlers -- - /// Functions that extract information about tool properties from - /// DAG representation. - - void onActions (const DagInit& d) { - CheckNumberOfArguments(d, 1); - Init* Case = d.getArg(0); - if (typeid(*Case) != typeid(DagInit) || - GetOperatorName(static_cast(*Case)) != "case") - throw "The argument to (actions) should be a 'case' construct!"; - toolDesc_.Actions = Case; - } - - void onCommand (const DagInit& d) { - CheckNumberOfArguments(d, 1); - toolDesc_.CmdLine = d.getArg(0); - } - - /// onInOutLanguage - Common implementation of on{In,Out}Language(). - void onInOutLanguage (const DagInit& d, StrVector& OutVec) { - CheckNumberOfArguments(d, 1); - - // Copy strings to the output vector. - for (unsigned i = 0, NumArgs = d.getNumArgs(); i < NumArgs; ++i) { - OutVec.push_back(InitPtrToString(d.getArg(i))); - } - - // Remove duplicates. - std::sort(OutVec.begin(), OutVec.end()); - StrVector::iterator newE = std::unique(OutVec.begin(), OutVec.end()); - OutVec.erase(newE, OutVec.end()); - } - - - void onInLanguage (const DagInit& d) { - this->onInOutLanguage(d, toolDesc_.InLanguage); - } - - void onJoin (const DagInit& d) { - bool isReallyJoin = false; - - if (d.getNumArgs() == 0) { - isReallyJoin = true; - } - else { - Init* I = d.getArg(0); - isReallyJoin = InitPtrToBool(I); - } - - // Is this *really* a join tool? We allow (join false) for generating two - // tool descriptions from a single generic one. - // TOFIX: come up with a cleaner solution. - if (isReallyJoin) { - toolDesc_.setJoin(); - } - } - - void onOutLanguage (const DagInit& d) { - this->onInOutLanguage(d, toolDesc_.OutLanguage); - } - - void onOutFileOption (const DagInit& d) { - CheckNumberOfArguments(d, 1); - toolDesc_.OutFileOption = InitPtrToString(d.getArg(0)); - } - - void onInFileOption (const DagInit& d) { - CheckNumberOfArguments(d, 1); - toolDesc_.InFileOption = InitPtrToString(d.getArg(0)); - } - - void onOutputSuffix (const DagInit& d) { - CheckNumberOfArguments(d, 1); - toolDesc_.OutputSuffix = InitPtrToString(d.getArg(0)); - } - - void onSink (const DagInit& d) { - CheckNumberOfArguments(d, 0); - toolDesc_.setSink(); - } - - void onWorksOnEmpty (const DagInit& d) { - toolDesc_.OnEmpty = d.getArg(0); - } - -}; - -/// CollectToolDescriptions - Gather information about tool properties -/// from the parsed TableGen data (basically a wrapper for the -/// CollectToolProperties function object). -void CollectToolDescriptions (const RecordVector& Tools, - ToolDescriptions& ToolDescs) -{ - // Iterate over a properties list of every Tool definition - for (RecordVector::const_iterator B = Tools.begin(), - E = Tools.end(); B!=E; ++B) { - const Record* T = *B; - // Throws an exception if the value does not exist. - ListInit* PropList = T->getValueAsListInit("properties"); - - IntrusiveRefCntPtr - ToolDesc(new ToolDescription(T->getName())); - - std::for_each(PropList->begin(), PropList->end(), - CollectToolProperties(*ToolDesc)); - ToolDescs.push_back(ToolDesc); - } -} - -/// FillInEdgeVector - Merge all compilation graph definitions into -/// one single edge list. -void FillInEdgeVector(const RecordVector& CompilationGraphs, - DagVector& Out) { - for (RecordVector::const_iterator B = CompilationGraphs.begin(), - E = CompilationGraphs.end(); B != E; ++B) { - const ListInit* Edges = (*B)->getValueAsListInit("edges"); - - for (ListInit::const_iterator B = Edges->begin(), - E = Edges->end(); B != E; ++B) { - Out.push_back(&InitPtrToDag(*B)); - } - } -} - -/// NotInGraph - Helper function object for FilterNotInGraph. -struct NotInGraph { -private: - const llvm::StringSet<>& ToolsInGraph_; - -public: - NotInGraph(const llvm::StringSet<>& ToolsInGraph) - : ToolsInGraph_(ToolsInGraph) - {} - - bool operator()(const IntrusiveRefCntPtr& x) { - return (ToolsInGraph_.count(x->Name) == 0); - } -}; - -/// FilterNotInGraph - Filter out from ToolDescs all Tools not -/// mentioned in the compilation graph definition. -void FilterNotInGraph (const DagVector& EdgeVector, - ToolDescriptions& ToolDescs) { - - // List all tools mentioned in the graph. - llvm::StringSet<> ToolsInGraph; - - for (DagVector::const_iterator B = EdgeVector.begin(), - E = EdgeVector.end(); B != E; ++B) { - - const DagInit* Edge = *B; - const std::string& NodeA = InitPtrToString(Edge->getArg(0)); - const std::string& NodeB = InitPtrToString(Edge->getArg(1)); - - if (NodeA != "root") - ToolsInGraph.insert(NodeA); - ToolsInGraph.insert(NodeB); - } - - // Filter ToolPropertiesList. - ToolDescriptions::iterator new_end = - std::remove_if(ToolDescs.begin(), ToolDescs.end(), - NotInGraph(ToolsInGraph)); - ToolDescs.erase(new_end, ToolDescs.end()); -} - -/// FillInToolToLang - Fills in two tables that map tool names to -/// input & output language names. Helper function used by TypecheckGraph(). -void FillInToolToLang (const ToolDescriptions& ToolDescs, - StringMap >& ToolToInLang, - StringMap >& ToolToOutLang) { - for (ToolDescriptions::const_iterator B = ToolDescs.begin(), - E = ToolDescs.end(); B != E; ++B) { - const ToolDescription& D = *(*B); - for (StrVector::const_iterator B = D.InLanguage.begin(), - E = D.InLanguage.end(); B != E; ++B) - ToolToInLang[D.Name].insert(*B); - for (StrVector::const_iterator B = D.OutLanguage.begin(), - E = D.OutLanguage.end(); B != E; ++B) - ToolToOutLang[D.Name].insert(*B); - } -} - -/// Intersect - Is set intersection non-empty? -bool Intersect (const StringSet<>& S1, const StringSet<>& S2) { - for (StringSet<>::const_iterator B = S1.begin(), E = S1.end(); B != E; ++B) { - if (S2.count(B->first()) != 0) - return true; - } - return false; -} - -/// TypecheckGraph - Check that names for output and input languages -/// on all edges do match. -void TypecheckGraph (const DagVector& EdgeVector, - const ToolDescriptions& ToolDescs) { - StringMap > ToolToInLang; - StringMap > ToolToOutLang; - - FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang); - - for (DagVector::const_iterator B = EdgeVector.begin(), - E = EdgeVector.end(); B != E; ++B) { - const DagInit* Edge = *B; - const std::string& NodeA = InitPtrToString(Edge->getArg(0)); - const std::string& NodeB = InitPtrToString(Edge->getArg(1)); - StringMap >::iterator IA = ToolToOutLang.find(NodeA); - StringMap >::iterator IB = ToolToInLang.find(NodeB); - - if (NodeB == "root") - throw "Edges back to the root are not allowed!"; - - if (NodeA != "root") { - if (IA == ToolToOutLang.end()) - throw NodeA + ": no output language defined!"; - if (IB == ToolToInLang.end()) - throw NodeB + ": no input language defined!"; - - if (!Intersect(IA->second, IB->second)) { - throw "Edge " + NodeA + "->" + NodeB - + ": output->input language mismatch"; - } - } - } -} - -/// WalkCase - Walks the 'case' expression DAG and invokes -/// TestCallback on every test, and StatementCallback on every -/// statement. Handles 'case' nesting, but not the 'and' and 'or' -/// combinators (that is, they are passed directly to TestCallback). -/// TestCallback must have type 'void TestCallback(const DagInit*, unsigned -/// IndentLevel, bool FirstTest)'. -/// StatementCallback must have type 'void StatementCallback(const Init*, -/// unsigned IndentLevel)'. -template -void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback, - unsigned IndentLevel = 0) -{ - const DagInit& d = InitPtrToDag(Case); - - // Error checks. - if (GetOperatorName(d) != "case") - throw "WalkCase should be invoked only on 'case' expressions!"; - - if (d.getNumArgs() < 2) - throw "There should be at least one clause in the 'case' expression:\n" - + d.getAsString(); - - // Main loop. - bool even = false; - const unsigned numArgs = d.getNumArgs(); - unsigned i = 1; - for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end(); - B != E; ++B) { - Init* arg = *B; - - if (!even) - { - // Handle test. - const DagInit& Test = InitPtrToDag(arg); - - if (GetOperatorName(Test) == "default" && (i+1 != numArgs)) - throw "The 'default' clause should be the last in the " - "'case' construct!"; - if (i == numArgs) - throw "Case construct handler: no corresponding action " - "found for the test " + Test.getAsString() + '!'; - - TestCallback(Test, IndentLevel, (i == 1)); - } - else - { - if (dynamic_cast(arg) - && GetOperatorName(static_cast(*arg)) == "case") { - // Nested 'case'. - WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1); - } - - // Handle statement. - StatementCallback(arg, IndentLevel); - } - - ++i; - even = !even; - } -} - -/// ExtractOptionNames - A helper function object used by -/// CheckForSuperfluousOptions() to walk the 'case' DAG. -class ExtractOptionNames { - llvm::StringSet<>& OptionNames_; - - void processDag(const Init* Statement) { - const DagInit& Stmt = InitPtrToDag(Statement); - const std::string& ActionName = GetOperatorName(Stmt); - if (ActionName == "forward" || ActionName == "forward_as" || - ActionName == "forward_value" || - ActionName == "forward_transformed_value" || - ActionName == "parameter_equals" || ActionName == "element_in_list") { - CheckNumberOfArguments(Stmt, 1); - - Init* Arg = Stmt.getArg(0); - if (typeid(*Arg) == typeid(StringInit)) - OptionNames_.insert(InitPtrToString(Arg)); - } - else if (ActionName == "any_switch_on" || ActionName == "switch_on" || - ActionName == "any_not_empty" || ActionName == "any_empty" || - ActionName == "not_empty" || ActionName == "empty") { - for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) { - Init* Arg = Stmt.getArg(i); - if (typeid(*Arg) == typeid(StringInit)) - OptionNames_.insert(InitPtrToString(Arg)); - } - } - else if (ActionName == "and" || ActionName == "or" || ActionName == "not") { - for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) { - this->processDag(Stmt.getArg(i)); - } - } - } - -public: - ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames) - {} - - void operator()(const Init* Statement) { - // Statement is either a dag, or a list of dags. - if (typeid(*Statement) == typeid(ListInit)) { - const ListInit& DagList = *static_cast(Statement); - for (ListInit::const_iterator B = DagList.begin(), E = DagList.end(); - B != E; ++B) - this->processDag(*B); - } - else { - this->processDag(Statement); - } - } - - void operator()(const DagInit& Test, unsigned, bool) { - this->operator()(&Test); - } - void operator()(const Init* Statement, unsigned) { - this->operator()(Statement); - } -}; - -/// IsOptionalEdge - Validate that the 'optional_edge' has proper structure. -bool IsOptionalEdge (const DagInit& Edg) { - return (GetOperatorName(Edg) == "optional_edge") && (Edg.getNumArgs() > 2); -} - -/// CheckForSuperfluousOptions - Check that there are no side -/// effect-free options (specified only in the OptionList). Otherwise, -/// output a warning. -void CheckForSuperfluousOptions (const DagVector& EdgeVector, - const ToolDescriptions& ToolDescs, - const OptionDescriptions& OptDescs) { - llvm::StringSet<> nonSuperfluousOptions; - - // Add all options mentioned in the ToolDesc.Actions to the set of - // non-superfluous options. - for (ToolDescriptions::const_iterator B = ToolDescs.begin(), - E = ToolDescs.end(); B != E; ++B) { - const ToolDescription& TD = *(*B); - ExtractOptionNames Callback(nonSuperfluousOptions); - if (TD.Actions) - WalkCase(TD.Actions, Callback, Callback); - } - - // Add all options mentioned in the 'case' clauses of the - // OptionalEdges of the compilation graph to the set of - // non-superfluous options. - for (DagVector::const_iterator B = EdgeVector.begin(), - E = EdgeVector.end(); B != E; ++B) { - const DagInit& Edge = **B; - if (IsOptionalEdge(Edge)) { - const DagInit& Weight = InitPtrToDag(Edge.getArg(2)); - WalkCase(&Weight, ExtractOptionNames(nonSuperfluousOptions), Id()); - } - } - - // Check that all options in OptDescs belong to the set of - // non-superfluous options. - for (OptionDescriptions::const_iterator B = OptDescs.begin(), - E = OptDescs.end(); B != E; ++B) { - const OptionDescription& Val = B->second; - if (!nonSuperfluousOptions.count(Val.Name) - && Val.Type != OptionType::Alias) - llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! " - "Probable cause: this option is specified only in the OptionList.\n"; - } -} - -/// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler(). -bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) { - if (TestName == "single_input_file") { - O << "InputFilenames.size() == 1"; - return true; - } - else if (TestName == "multiple_input_files") { - O << "InputFilenames.size() > 1"; - return true; - } - - return false; -} - -/// EmitMultipleArgumentTest - Helper function used by -/// EmitCaseTestMultipleArgs() -template -void EmitMultipleArgumentTest(const DagInit& D, const char* LogicOp, - F Callback, raw_ostream& O) -{ - for (unsigned i = 0, NumArgs = D.getNumArgs(); i < NumArgs; ++i) { - if (i != 0) - O << ' ' << LogicOp << ' '; - Callback(InitPtrToString(D.getArg(i)), O); - } -} - -// Callbacks for use with EmitMultipleArgumentTest - -class EmitSwitchOn { - const OptionDescriptions& OptDescs_; -public: - EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs) - {} - - void operator()(const std::string& OptName, raw_ostream& O) const { - const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName); - O << OptDesc.GenVariableName(); - } -}; - -class EmitEmptyTest { - bool EmitNegate_; - const OptionDescriptions& OptDescs_; -public: - EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs) - : EmitNegate_(EmitNegate), OptDescs_(OptDescs) - {} - - void operator()(const std::string& OptName, raw_ostream& O) const { - const char* Neg = (EmitNegate_ ? "!" : ""); - if (OptName == "o") { - O << Neg << "OutputFilename.empty()"; - } - else if (OptName == "save-temps") { - O << Neg << "(SaveTemps == SaveTempsEnum::Unset)"; - } - else { - const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName); - O << Neg << OptDesc.GenVariableName() << ".empty()"; - } - } -}; - - -/// EmitCaseTestMultipleArgs - Helper function used by EmitCaseTest1Arg() -bool EmitCaseTestMultipleArgs (const std::string& TestName, - const DagInit& d, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - if (TestName == "any_switch_on") { - EmitMultipleArgumentTest(d, "||", EmitSwitchOn(OptDescs), O); - return true; - } - else if (TestName == "switch_on") { - EmitMultipleArgumentTest(d, "&&", EmitSwitchOn(OptDescs), O); - return true; - } - else if (TestName == "any_not_empty") { - EmitMultipleArgumentTest(d, "||", EmitEmptyTest(true, OptDescs), O); - return true; - } - else if (TestName == "any_empty") { - EmitMultipleArgumentTest(d, "||", EmitEmptyTest(false, OptDescs), O); - return true; - } - else if (TestName == "not_empty") { - EmitMultipleArgumentTest(d, "&&", EmitEmptyTest(true, OptDescs), O); - return true; - } - else if (TestName == "empty") { - EmitMultipleArgumentTest(d, "&&", EmitEmptyTest(false, OptDescs), O); - return true; - } - - return false; -} - -/// EmitCaseTest1Arg - Helper function used by EmitCaseTest1OrMoreArgs() -bool EmitCaseTest1Arg (const std::string& TestName, - const DagInit& d, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - const std::string& Arg = InitPtrToString(d.getArg(0)); - - if (TestName == "input_languages_contain") { - O << "InLangs.count(\"" << Arg << "\") != 0"; - return true; - } - else if (TestName == "in_language") { - // This works only for single-argument Tool::GenerateAction. Join - // tools can process several files in different languages simultaneously. - - // TODO: make this work with Edge::Weight (if possible). - O << "LangMap.GetLanguage(inFile) == \"" << Arg << '\"'; - return true; - } - - return false; -} - -/// EmitCaseTest1OrMoreArgs - Helper function used by -/// EmitCaseConstructHandler() -bool EmitCaseTest1OrMoreArgs(const std::string& TestName, - const DagInit& d, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - CheckNumberOfArguments(d, 1); - return EmitCaseTest1Arg(TestName, d, OptDescs, O) || - EmitCaseTestMultipleArgs(TestName, d, OptDescs, O); -} - -/// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler(). -bool EmitCaseTest2Args(const std::string& TestName, - const DagInit& d, - unsigned IndentLevel, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - CheckNumberOfArguments(d, 2); - const std::string& OptName = InitPtrToString(d.getArg(0)); - const std::string& OptArg = InitPtrToString(d.getArg(1)); - - if (TestName == "parameter_equals") { - const OptionDescription& OptDesc = OptDescs.FindParameter(OptName); - O << OptDesc.GenVariableName() << " == \"" << OptArg << "\""; - return true; - } - else if (TestName == "element_in_list") { - const OptionDescription& OptDesc = OptDescs.FindParameterList(OptName); - const std::string& VarName = OptDesc.GenVariableName(); - O << "std::find(" << VarName << ".begin(),\n"; - O.indent(IndentLevel + Indent1) - << VarName << ".end(), \"" - << OptArg << "\") != " << VarName << ".end()"; - return true; - } - - return false; -} - -// Forward declaration. -// EmitLogicalOperationTest and EmitCaseTest are mutually recursive. -void EmitCaseTest(const DagInit& d, unsigned IndentLevel, - const OptionDescriptions& OptDescs, - raw_ostream& O); - -/// EmitLogicalOperationTest - Helper function used by -/// EmitCaseConstructHandler. -void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp, - unsigned IndentLevel, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - O << '('; - for (unsigned i = 0, NumArgs = d.getNumArgs(); i < NumArgs; ++i) { - const DagInit& InnerTest = InitPtrToDag(d.getArg(i)); - EmitCaseTest(InnerTest, IndentLevel, OptDescs, O); - if (i != NumArgs - 1) { - O << ")\n"; - O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " ("; - } - else { - O << ')'; - } - } -} - -void EmitLogicalNot(const DagInit& d, unsigned IndentLevel, - const OptionDescriptions& OptDescs, raw_ostream& O) -{ - CheckNumberOfArguments(d, 1); - const DagInit& InnerTest = InitPtrToDag(d.getArg(0)); - O << "! ("; - EmitCaseTest(InnerTest, IndentLevel, OptDescs, O); - O << ")"; -} - -/// EmitCaseTest - Helper function used by EmitCaseConstructHandler. -void EmitCaseTest(const DagInit& d, unsigned IndentLevel, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - const std::string& TestName = GetOperatorName(d); - - if (TestName == "and") - EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O); - else if (TestName == "or") - EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O); - else if (TestName == "not") - EmitLogicalNot(d, IndentLevel, OptDescs, O); - else if (EmitCaseTest0Args(TestName, O)) - return; - else if (EmitCaseTest1OrMoreArgs(TestName, d, OptDescs, O)) - return; - else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O)) - return; - else - throw "Unknown test '" + TestName + "' used in the 'case' construct!"; -} - - -/// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler. -class EmitCaseTestCallback { - bool EmitElseIf_; - const OptionDescriptions& OptDescs_; - raw_ostream& O_; -public: - - EmitCaseTestCallback(bool EmitElseIf, - const OptionDescriptions& OptDescs, raw_ostream& O) - : EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O) - {} - - void operator()(const DagInit& Test, unsigned IndentLevel, bool FirstTest) - { - if (GetOperatorName(Test) == "default") { - O_.indent(IndentLevel) << "else {\n"; - } - else { - O_.indent(IndentLevel) - << ((!FirstTest && EmitElseIf_) ? "else if (" : "if ("); - EmitCaseTest(Test, IndentLevel, OptDescs_, O_); - O_ << ") {\n"; - } - } -}; - -/// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler. -template -class EmitCaseStatementCallback { - F Callback_; - raw_ostream& O_; -public: - - EmitCaseStatementCallback(F Callback, raw_ostream& O) - : Callback_(Callback), O_(O) - {} - - void operator() (const Init* Statement, unsigned IndentLevel) { - // Is this a nested 'case'? - bool IsCase = dynamic_cast(Statement) && - GetOperatorName(static_cast(*Statement)) == "case"; - - // If so, ignore it, it is handled by our caller, WalkCase. - if (!IsCase) { - if (typeid(*Statement) == typeid(ListInit)) { - const ListInit& DagList = *static_cast(Statement); - for (ListInit::const_iterator B = DagList.begin(), E = DagList.end(); - B != E; ++B) - Callback_(*B, (IndentLevel + Indent1), O_); - } - else { - Callback_(Statement, (IndentLevel + Indent1), O_); - } - } - O_.indent(IndentLevel) << "}\n"; - } - -}; - -/// EmitCaseConstructHandler - Emit code that handles the 'case' -/// construct. Takes a function object that should emit code for every case -/// clause. Implemented on top of WalkCase. -/// Callback's type is void F(const Init* Statement, unsigned IndentLevel, -/// raw_ostream& O). -/// EmitElseIf parameter controls the type of condition that is emitted ('if -/// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..} -/// .. else {..}'). -template -void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel, - F Callback, bool EmitElseIf, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O), - EmitCaseStatementCallback(Callback, O), IndentLevel); -} - -/// TokenizeCmdLine - converts from -/// "$CALL(HookName, 'Arg1', 'Arg2')/path -arg1 -arg2" to -/// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path", "-arg1", "-arg2"]. -void TokenizeCmdLine(const std::string& CmdLine, StrVector& Out) { - const char* Delimiters = " \t\n\v\f\r"; - enum TokenizerState - { Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks } - cur_st = Normal; - - if (CmdLine.empty()) - return; - Out.push_back(""); - - std::string::size_type B = CmdLine.find_first_not_of(Delimiters), - E = CmdLine.size(); - - for (; B != E; ++B) { - char cur_ch = CmdLine[B]; - - switch (cur_st) { - case Normal: - if (cur_ch == '$') { - cur_st = SpecialCommand; - break; - } - if (OneOf(Delimiters, cur_ch)) { - // Skip whitespace - B = CmdLine.find_first_not_of(Delimiters, B); - if (B == std::string::npos) { - B = E-1; - continue; - } - --B; - Out.push_back(""); - continue; - } - break; - - - case SpecialCommand: - if (OneOf(Delimiters, cur_ch)) { - cur_st = Normal; - Out.push_back(""); - continue; - } - if (cur_ch == '(') { - Out.push_back(""); - cur_st = InsideSpecialCommand; - continue; - } - break; - - case InsideSpecialCommand: - if (OneOf(Delimiters, cur_ch)) { - continue; - } - if (cur_ch == '\'') { - cur_st = InsideQuotationMarks; - Out.push_back(""); - continue; - } - if (cur_ch == ')') { - cur_st = Normal; - Out.push_back(""); - } - if (cur_ch == ',') { - continue; - } - - break; - - case InsideQuotationMarks: - if (cur_ch == '\'') { - cur_st = InsideSpecialCommand; - continue; - } - break; - } - - Out.back().push_back(cur_ch); - } -} - -/// SubstituteCall - Given "$CALL(HookName, [Arg1 [, Arg2 [...]]])", output -/// "hooks::HookName([Arg1 [, Arg2 [, ...]]])". Helper function used by -/// SubstituteSpecialCommands(). -StrVector::const_iterator -SubstituteCall (StrVector::const_iterator Pos, - StrVector::const_iterator End, - bool IsJoin, raw_ostream& O) -{ - const char* errorMessage = "Syntax error in $CALL invocation!"; - CheckedIncrement(Pos, End, errorMessage); - const std::string& CmdName = *Pos; - - if (CmdName == ")") - throw "$CALL invocation: empty argument list!"; - - O << "hooks::"; - O << CmdName << "("; - - - bool firstIteration = true; - while (true) { - CheckedIncrement(Pos, End, errorMessage); - const std::string& Arg = *Pos; - assert(Arg.size() != 0); - - if (Arg[0] == ')') - break; - - if (firstIteration) - firstIteration = false; - else - O << ", "; - - if (Arg == "$INFILE") { - if (IsJoin) - throw "$CALL(Hook, $INFILE) can't be used with a Join tool!"; - else - O << "inFile.c_str()"; - } - else { - O << '"' << Arg << '"'; - } - } - - O << ')'; - - return Pos; -} - -/// SubstituteEnv - Given '$ENV(VAR_NAME)', output 'getenv("VAR_NAME")'. Helper -/// function used by SubstituteSpecialCommands(). -StrVector::const_iterator -SubstituteEnv (StrVector::const_iterator Pos, - StrVector::const_iterator End, raw_ostream& O) -{ - const char* errorMessage = "Syntax error in $ENV invocation!"; - CheckedIncrement(Pos, End, errorMessage); - const std::string& EnvName = *Pos; - - if (EnvName == ")") - throw "$ENV invocation: empty argument list!"; - - O << "checkCString(std::getenv(\""; - O << EnvName; - O << "\"))"; - - CheckedIncrement(Pos, End, errorMessage); - - return Pos; -} - -/// SubstituteSpecialCommands - Given an invocation of $CALL or $ENV, output -/// handler code. Helper function used by EmitCmdLineVecFill(). -StrVector::const_iterator -SubstituteSpecialCommands (StrVector::const_iterator Pos, - StrVector::const_iterator End, - bool IsJoin, raw_ostream& O) -{ - - const std::string& cmd = *Pos; - - // Perform substitution. - if (cmd == "$CALL") { - Pos = SubstituteCall(Pos, End, IsJoin, O); - } - else if (cmd == "$ENV") { - Pos = SubstituteEnv(Pos, End, O); - } - else { - throw "Unknown special command: " + cmd; - } - - // Handle '$CMD(ARG)/additional/text'. - const std::string& Leftover = *Pos; - assert(Leftover.at(0) == ')'); - if (Leftover.size() != 1) - O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")"; - - return Pos; -} - -/// EmitCmdLineVecFill - Emit code that fills in the command line -/// vector. Helper function used by EmitGenerateActionMethod(). -void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName, - bool IsJoin, unsigned IndentLevel, - raw_ostream& O) { - StrVector StrVec; - TokenizeCmdLine(InitPtrToString(CmdLine), StrVec); - - if (StrVec.empty()) - throw "Tool '" + ToolName + "' has empty command line!"; - - StrVector::const_iterator B = StrVec.begin(), E = StrVec.end(); - - // Emit the command itself. - assert(!StrVec[0].empty()); - O.indent(IndentLevel) << "cmd = "; - if (StrVec[0][0] == '$') { - B = SubstituteSpecialCommands(B, E, IsJoin, O); - ++B; - } - else { - O << '"' << StrVec[0] << '"'; - ++B; - } - O << ";\n"; - - // Go through the command arguments. - assert(B <= E); - for (; B != E; ++B) { - const std::string& cmd = *B; - - assert(!cmd.empty()); - O.indent(IndentLevel); - - if (cmd.at(0) == '$') { - O << "vec.push_back(std::make_pair(0, "; - B = SubstituteSpecialCommands(B, E, IsJoin, O); - O << "));\n"; - } - else { - O << "vec.push_back(std::make_pair(0, \"" << cmd << "\"));\n"; - } - } - -} - -/// EmitForEachListElementCycleHeader - Emit common code for iterating through -/// all elements of a list. Helper function used by -/// EmitForwardOptionPropertyHandlingCode. -void EmitForEachListElementCycleHeader (const OptionDescription& D, - unsigned IndentLevel, - raw_ostream& O) { - unsigned IndentLevel1 = IndentLevel + Indent1; - - O.indent(IndentLevel) - << "for (" << D.GenTypeDeclaration() - << "::iterator B = " << D.GenVariableName() << ".begin(),\n"; - O.indent(IndentLevel) - << "E = " << D.GenVariableName() << ".end(); B != E;) {\n"; - O.indent(IndentLevel1) << "unsigned pos = " << D.GenVariableName() - << ".getPosition(B - " << D.GenVariableName() - << ".begin());\n"; -} - -/// EmitForwardOptionPropertyHandlingCode - Helper function used to -/// implement EmitActionHandler. Emits code for -/// handling the (forward) and (forward_as) option properties. -void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D, - unsigned IndentLevel, - const std::string& NewName, - raw_ostream& O) { - const std::string& Name = NewName.empty() - ? ("-" + D.Name) - : NewName; - unsigned IndentLevel1 = IndentLevel + Indent1; - - switch (D.Type) { - case OptionType::Switch: - O.indent(IndentLevel) - << "vec.push_back(std::make_pair(" << D.GenVariableName() - << ".getPosition(), \"" << Name << "\"));\n"; - break; - case OptionType::Parameter: - O.indent(IndentLevel) << "vec.push_back(std::make_pair(" - << D.GenVariableName() - <<".getPosition(), \"" << Name; - - if (!D.isForwardNotSplit()) { - O << "\"));\n"; - O.indent(IndentLevel) << "vec.push_back(std::make_pair(" - << D.GenVariableName() << ".getPosition(), " - << D.GenVariableName() << "));\n"; - } - else { - O << "=\" + " << D.GenVariableName() << "));\n"; - } - break; - case OptionType::Prefix: - O.indent(IndentLevel) << "vec.push_back(std::make_pair(" - << D.GenVariableName() << ".getPosition(), \"" - << Name << "\" + " - << D.GenVariableName() << "));\n"; - break; - case OptionType::PrefixList: - EmitForEachListElementCycleHeader(D, IndentLevel, O); - O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \"" - << Name << "\" + " << "*B));\n"; - O.indent(IndentLevel1) << "++B;\n"; - - for (int i = 1, j = D.MultiVal; i < j; ++i) { - O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n"; - O.indent(IndentLevel1) << "++B;\n"; - } - - O.indent(IndentLevel) << "}\n"; - break; - case OptionType::ParameterList: - EmitForEachListElementCycleHeader(D, IndentLevel, O); - O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \"" - << Name << "\"));\n"; - - for (int i = 0, j = D.MultiVal; i < j; ++i) { - O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, *B));\n"; - O.indent(IndentLevel1) << "++B;\n"; - } - - O.indent(IndentLevel) << "}\n"; - break; - case OptionType::SwitchList: - EmitForEachListElementCycleHeader(D, IndentLevel, O); - O.indent(IndentLevel1) << "vec.push_back(std::make_pair(pos, \"" - << Name << "\"));\n"; - O.indent(IndentLevel1) << "++B;\n"; - O.indent(IndentLevel) << "}\n"; - break; - case OptionType::Alias: - default: - throw "Aliases are not allowed in tool option descriptions!"; - } -} - -/// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and -/// EmitPreprocessOptionsCallback. -struct ActionHandlingCallbackBase -{ - - void onErrorDag(const DagInit& d, - unsigned IndentLevel, raw_ostream& O) const - { - O.indent(IndentLevel) - << "PrintError(\"" - << (d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0)) : "Unknown error!") - << "\");\n"; - O.indent(IndentLevel) << "return 1;\n"; - } - - void onWarningDag(const DagInit& d, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(d, 1); - O.indent(IndentLevel) << "llvm::errs() << \"" - << InitPtrToString(d.getArg(0)) << "\";\n"; - } - -}; - -/// EmitActionHandlersCallback - Emit code that handles actions. Used by -/// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler(). -class EmitActionHandlersCallback; - -typedef void (EmitActionHandlersCallback::* EmitActionHandlersCallbackHandler) -(const DagInit&, unsigned, raw_ostream&) const; - -class EmitActionHandlersCallback : - public ActionHandlingCallbackBase, - public HandlerTable -{ - typedef EmitActionHandlersCallbackHandler Handler; - - const OptionDescriptions& OptDescs; - - /// EmitHookInvocation - Common code for hook invocation from actions. Used by - /// onAppendCmd and onOutputSuffix. - void EmitHookInvocation(const std::string& Str, - const char* BlockOpen, const char* BlockClose, - unsigned IndentLevel, raw_ostream& O) const - { - StrVector Out; - TokenizeCmdLine(Str, Out); - - for (StrVector::const_iterator B = Out.begin(), E = Out.end(); - B != E; ++B) { - const std::string& cmd = *B; - - O.indent(IndentLevel) << BlockOpen; - - if (cmd.at(0) == '$') - B = SubstituteSpecialCommands(B, E, /* IsJoin = */ true, O); - else - O << '"' << cmd << '"'; - - O << BlockClose; - } - } - - void onAppendCmd (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 1); - this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)), - "vec.push_back(std::make_pair(65536, ", "));\n", - IndentLevel, O); - } - - void onForward (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 1); - const std::string& Name = InitPtrToString(Dag.getArg(0)); - EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name), - IndentLevel, "", O); - } - - void onForwardAs (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 2); - const std::string& Name = InitPtrToString(Dag.getArg(0)); - const std::string& NewName = InitPtrToString(Dag.getArg(1)); - EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name), - IndentLevel, NewName, O); - } - - void onForwardValue (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 1); - const std::string& Name = InitPtrToString(Dag.getArg(0)); - const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name); - - if (D.isSwitchList()) { - throw std::runtime_error - ("forward_value is not allowed with switch_list"); - } - - if (D.isParameter()) { - O.indent(IndentLevel) << "vec.push_back(std::make_pair(" - << D.GenVariableName() << ".getPosition(), " - << D.GenVariableName() << "));\n"; - } - else { - O.indent(IndentLevel) << "for (" << D.GenTypeDeclaration() - << "::iterator B = " << D.GenVariableName() - << ".begin(), \n"; - O.indent(IndentLevel + Indent1) << " E = " << D.GenVariableName() - << ".end(); B != E; ++B)\n"; - O.indent(IndentLevel) << "{\n"; - O.indent(IndentLevel + Indent1) - << "unsigned pos = " << D.GenVariableName() - << ".getPosition(B - " << D.GenVariableName() - << ".begin());\n"; - O.indent(IndentLevel + Indent1) - << "vec.push_back(std::make_pair(pos, *B));\n"; - O.indent(IndentLevel) << "}\n"; - } - } - - void onForwardTransformedValue (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 2); - const std::string& Name = InitPtrToString(Dag.getArg(0)); - const std::string& Hook = InitPtrToString(Dag.getArg(1)); - const OptionDescription& D = OptDescs.FindParameterListOrParameter(Name); - - O.indent(IndentLevel) << "vec.push_back(std::make_pair(" - << D.GenVariableName() << ".getPosition(" - << (D.isList() ? "0" : "") << "), " - << "hooks::" << Hook << "(" << D.GenVariableName() - << (D.isParameter() ? ".c_str()" : "") << ")));\n"; - } - - void onNoOutFile (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 0); - O.indent(IndentLevel) << "no_out_file = true;\n"; - } - - void onOutputSuffix (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(Dag, 1); - this->EmitHookInvocation(InitPtrToString(Dag.getArg(0)), - "output_suffix = ", ";\n", IndentLevel, O); - } - - void onStopCompilation (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - O.indent(IndentLevel) << "stop_compilation = true;\n"; - } - - - void onUnpackValues (const DagInit& Dag, - unsigned IndentLevel, raw_ostream& O) const - { - throw "'unpack_values' is deprecated. " - "Use 'comma_separated' + 'forward_value' instead!"; - } - - public: - - explicit EmitActionHandlersCallback(const OptionDescriptions& OD) - : OptDescs(OD) - { - if (!staticMembersInitialized_) { - AddHandler("error", &EmitActionHandlersCallback::onErrorDag); - AddHandler("warning", &EmitActionHandlersCallback::onWarningDag); - AddHandler("append_cmd", &EmitActionHandlersCallback::onAppendCmd); - AddHandler("forward", &EmitActionHandlersCallback::onForward); - AddHandler("forward_as", &EmitActionHandlersCallback::onForwardAs); - AddHandler("forward_value", &EmitActionHandlersCallback::onForwardValue); - AddHandler("forward_transformed_value", - &EmitActionHandlersCallback::onForwardTransformedValue); - AddHandler("no_out_file", - &EmitActionHandlersCallback::onNoOutFile); - AddHandler("output_suffix", &EmitActionHandlersCallback::onOutputSuffix); - AddHandler("stop_compilation", - &EmitActionHandlersCallback::onStopCompilation); - AddHandler("unpack_values", - &EmitActionHandlersCallback::onUnpackValues); - - - staticMembersInitialized_ = true; - } - } - - void operator()(const Init* I, - unsigned IndentLevel, raw_ostream& O) const - { - InvokeDagInitHandler(this, I, IndentLevel, O); - } -}; - -void EmitGenerateActionMethodHeader(const ToolDescription& D, - bool IsJoin, bool Naked, - raw_ostream& O) -{ - O.indent(Indent1) << "int GenerateAction(Action& Out,\n"; - - if (IsJoin) - O.indent(Indent2) << "const PathVector& inFiles,\n"; - else - O.indent(Indent2) << "const sys::Path& inFile,\n"; - - O.indent(Indent2) << "const bool HasChildren,\n"; - O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n"; - O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n"; - O.indent(Indent2) << "const LanguageMap& LangMap) const\n"; - O.indent(Indent1) << "{\n"; - - if (!Naked) { - O.indent(Indent2) << "std::string cmd;\n"; - O.indent(Indent2) << "std::string out_file;\n"; - O.indent(Indent2) - << "std::vector > vec;\n"; - O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n"; - O.indent(Indent2) << "bool no_out_file = false;\n"; - O.indent(Indent2) << "std::string output_suffix(\"" - << D.OutputSuffix << "\");\n"; - } -} - -// EmitGenerateActionMethod - Emit either a normal or a "join" version of the -// Tool::GenerateAction() method. -void EmitGenerateActionMethod (const ToolDescription& D, - const OptionDescriptions& OptDescs, - bool IsJoin, raw_ostream& O) { - - EmitGenerateActionMethodHeader(D, IsJoin, /* Naked = */ false, O); - - if (!D.CmdLine) - throw "Tool " + D.Name + " has no cmd_line property!"; - - // Process the 'command' property. - O << '\n'; - EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O); - O << '\n'; - - // Process the 'actions' list of this tool. - if (D.Actions) - EmitCaseConstructHandler(D.Actions, Indent2, - EmitActionHandlersCallback(OptDescs), - false, OptDescs, O); - O << '\n'; - - // Input file (s) - if (!D.InFileOption.empty()) { - O.indent(Indent2) - << "vec.push_back(std::make_pair(InputFilenames.getPosition(0), \"" - << D.InFileOption << "\");\n"; - } - - if (IsJoin) { - O.indent(Indent2) - << "for (PathVector::const_iterator B = inFiles.begin(),\n"; - O.indent(Indent3) << "E = inFiles.end(); B != E; ++B)\n"; - O.indent(Indent2) << "{\n"; - O.indent(Indent3) << "vec.push_back(std::make_pair(" - << "InputFilenames.getPosition(B - inFiles.begin()), " - << "B->str()));\n"; - O.indent(Indent2) << "}\n"; - } - else { - O.indent(Indent2) << "vec.push_back(std::make_pair(" - << "InputFilenames.getPosition(0), inFile.str()));\n"; - } - - // Output file - O.indent(Indent2) << "if (!no_out_file) {\n"; - if (!D.OutFileOption.empty()) - O.indent(Indent3) << "vec.push_back(std::make_pair(65536, \"" - << D.OutFileOption << "\"));\n"; - - O.indent(Indent3) << "out_file = this->OutFilename(" - << (IsJoin ? "sys::Path(),\n" : "inFile,\n"); - O.indent(Indent4) << - "TempDir, stop_compilation, output_suffix.c_str()).str();\n\n"; - O.indent(Indent3) << "vec.push_back(std::make_pair(65536, out_file));\n"; - - O.indent(Indent2) << "}\n\n"; - - // Handle the Sink property. - std::string SinkOption("autogenerated::"); - SinkOption += SinkOptionName; - if (D.isSink()) { - O.indent(Indent2) << "if (!" << SinkOption << ".empty()) {\n"; - O.indent(Indent3) << "for (cl::list::iterator B = " - << SinkOption << ".begin(), E = " << SinkOption - << ".end(); B != E; ++B)\n"; - O.indent(Indent4) << "vec.push_back(std::make_pair(" << SinkOption - << ".getPosition(B - " << SinkOption - << ".begin()), *B));\n"; - O.indent(Indent2) << "}\n"; - } - - O.indent(Indent2) << "Out.Construct(cmd, this->SortArgs(vec), " - << "stop_compilation, out_file);\n"; - O.indent(Indent2) << "return 0;\n"; - O.indent(Indent1) << "}\n\n"; -} - -/// EmitGenerateActionMethods - Emit two GenerateAction() methods for -/// a given Tool class. -void EmitGenerateActionMethods (const ToolDescription& ToolDesc, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - if (!ToolDesc.isJoin()) { - EmitGenerateActionMethodHeader(ToolDesc, /* IsJoin = */ true, - /* Naked = */ true, O); - O.indent(Indent2) << "PrintError(\"" << ToolDesc.Name - << " is not a Join tool!\");\n"; - O.indent(Indent2) << "return -1;\n"; - O.indent(Indent1) << "}\n\n"; - } - else { - EmitGenerateActionMethod(ToolDesc, OptDescs, true, O); - } - - EmitGenerateActionMethod(ToolDesc, OptDescs, false, O); -} - -/// EmitInOutLanguageMethods - Emit the [Input,Output]Language() -/// methods for a given Tool class. -void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) { - O.indent(Indent1) << "const char** InputLanguages() const {\n"; - O.indent(Indent2) << "return InputLanguages_;\n"; - O.indent(Indent1) << "}\n\n"; - - O.indent(Indent1) << "const char** OutputLanguages() const {\n"; - O.indent(Indent2) << "return OutputLanguages_;\n"; - O.indent(Indent1) << "}\n\n"; -} - -/// EmitNameMethod - Emit the Name() method for a given Tool class. -void EmitNameMethod (const ToolDescription& D, raw_ostream& O) { - O.indent(Indent1) << "const char* Name() const {\n"; - O.indent(Indent2) << "return \"" << D.Name << "\";\n"; - O.indent(Indent1) << "}\n\n"; -} - -/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool -/// class. -void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) { - O.indent(Indent1) << "bool IsJoin() const {\n"; - if (D.isJoin()) - O.indent(Indent2) << "return true;\n"; - else - O.indent(Indent2) << "return false;\n"; - O.indent(Indent1) << "}\n\n"; -} - -/// EmitWorksOnEmptyCallback - Callback used by EmitWorksOnEmptyMethod in -/// conjunction with EmitCaseConstructHandler. -void EmitWorksOnEmptyCallback (const Init* Value, - unsigned IndentLevel, raw_ostream& O) { - CheckBooleanConstant(Value); - O.indent(IndentLevel) << "return " << Value->getAsString() << ";\n"; -} - -/// EmitWorksOnEmptyMethod - Emit the WorksOnEmpty() method for a given Tool -/// class. -void EmitWorksOnEmptyMethod (const ToolDescription& D, - const OptionDescriptions& OptDescs, - raw_ostream& O) -{ - O.indent(Indent1) << "bool WorksOnEmpty() const {\n"; - if (D.OnEmpty == 0) - O.indent(Indent2) << "return false;\n"; - else - EmitCaseConstructHandler(D.OnEmpty, Indent2, EmitWorksOnEmptyCallback, - /*EmitElseIf = */ true, OptDescs, O); - O.indent(Indent1) << "}\n\n"; -} - -/// EmitStrArray - Emit definition of a 'const char**' static member -/// variable. Helper used by EmitStaticMemberDefinitions(); -void EmitStrArray(const std::string& Name, const std::string& VarName, - const StrVector& StrVec, raw_ostream& O) { - O << "const char* " << Name << "::" << VarName << "[] = {"; - for (StrVector::const_iterator B = StrVec.begin(), E = StrVec.end(); - B != E; ++B) - O << '\"' << *B << "\", "; - O << "0};\n"; -} - -/// EmitStaticMemberDefinitions - Emit static member definitions for a -/// given Tool class. -void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) { - if (D.InLanguage.empty()) - throw "Tool " + D.Name + " has no 'in_language' property!"; - if (D.OutLanguage.empty()) - throw "Tool " + D.Name + " has no 'out_language' property!"; - - EmitStrArray(D.Name, "InputLanguages_", D.InLanguage, O); - EmitStrArray(D.Name, "OutputLanguages_", D.OutLanguage, O); - O << '\n'; -} - -/// EmitToolClassDefinition - Emit a Tool class definition. -void EmitToolClassDefinition (const ToolDescription& D, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - if (D.Name == "root") - return; - - // Header - O << "class " << D.Name << " : public "; - if (D.isJoin()) - O << "JoinTool"; - else - O << "Tool"; - - O << " {\nprivate:\n"; - O.indent(Indent1) << "static const char* InputLanguages_[];\n"; - O.indent(Indent1) << "static const char* OutputLanguages_[];\n\n"; - - O << "public:\n"; - EmitNameMethod(D, O); - EmitInOutLanguageMethods(D, O); - EmitIsJoinMethod(D, O); - EmitWorksOnEmptyMethod(D, OptDescs, O); - EmitGenerateActionMethods(D, OptDescs, O); - - // Close class definition - O << "};\n"; - - EmitStaticMemberDefinitions(D, O); - -} - -/// EmitOptionDefinitions - Iterate over a list of option descriptions -/// and emit registration code. -void EmitOptionDefinitions (const OptionDescriptions& descs, - bool HasSink, raw_ostream& O) -{ - std::vector Aliases; - - // Emit static cl::Option variables. - for (OptionDescriptions::const_iterator B = descs.begin(), - E = descs.end(); B!=E; ++B) { - const OptionDescription& val = B->second; - - if (val.Type == OptionType::Alias) { - Aliases.push_back(val); - continue; - } - - O << val.GenTypeDeclaration() << ' ' - << val.GenPlainVariableName(); - - O << "(\"" << val.Name << "\"\n"; - - if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList) - O << ", cl::Prefix"; - - if (val.isRequired()) { - if (val.isList() && !val.isMultiVal()) - O << ", cl::OneOrMore"; - else - O << ", cl::Required"; - } - - if (val.isOptional()) - O << ", cl::Optional"; - - if (val.isOneOrMore()) - O << ", cl::OneOrMore"; - - if (val.isZeroOrMore()) - O << ", cl::ZeroOrMore"; - - if (val.isReallyHidden()) - O << ", cl::ReallyHidden"; - else if (val.isHidden()) - O << ", cl::Hidden"; - - if (val.isCommaSeparated()) - O << ", cl::CommaSeparated"; - - if (val.MultiVal > 1) - O << ", cl::multi_val(" << val.MultiVal << ')'; - - if (val.InitVal) { - const std::string& str = val.InitVal->getAsString(); - O << ", cl::init(" << str << ')'; - } - - if (!val.Help.empty()) - O << ", cl::desc(\"" << val.Help << "\")"; - - O << ");\n\n"; - } - - // Emit the aliases (they should go after all the 'proper' options). - for (std::vector::const_iterator - B = Aliases.begin(), E = Aliases.end(); B != E; ++B) { - const OptionDescription& val = *B; - - O << val.GenTypeDeclaration() << ' ' - << val.GenPlainVariableName() - << "(\"" << val.Name << '\"'; - - const OptionDescription& D = descs.FindOption(val.Help); - O << ", cl::aliasopt(" << D.GenVariableName() << ")"; - - O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n"; - } - - // Emit the sink option. - if (HasSink) - O << "cl::list " << SinkOptionName << "(cl::Sink);\n"; - - O << '\n'; -} - -/// EmitPreprocessOptionsCallback - Helper function passed to -/// EmitCaseConstructHandler() by EmitPreprocessOptions(). - -class EmitPreprocessOptionsCallback; - -typedef void -(EmitPreprocessOptionsCallback::* EmitPreprocessOptionsCallbackHandler) -(const DagInit&, unsigned, raw_ostream&) const; - -class EmitPreprocessOptionsCallback : - public ActionHandlingCallbackBase, - public HandlerTable -{ - typedef EmitPreprocessOptionsCallbackHandler Handler; - typedef void - (EmitPreprocessOptionsCallback::* HandlerImpl) - (const Init*, unsigned, raw_ostream&) const; - - const OptionDescriptions& OptDescs_; - - void onEachArgument(const DagInit& d, HandlerImpl h, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(d, 1); - - for (unsigned i = 0, NumArgs = d.getNumArgs(); i < NumArgs; ++i) { - ((this)->*(h))(d.getArg(i), IndentLevel, O); - } - } - - void onUnsetOptionImpl(const Init* I, - unsigned IndentLevel, raw_ostream& O) const - { - const std::string& OptName = InitPtrToString(I); - const OptionDescription& OptDesc = OptDescs_.FindOption(OptName); - - if (OptDesc.isSwitch()) { - O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n"; - } - else if (OptDesc.isParameter()) { - O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n"; - } - else if (OptDesc.isList()) { - O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n"; - } - else { - throw "Can't apply 'unset_option' to alias option '" + OptName + "'!"; - } - } - - void onUnsetOption(const DagInit& d, - unsigned IndentLevel, raw_ostream& O) const - { - this->onEachArgument(d, &EmitPreprocessOptionsCallback::onUnsetOptionImpl, - IndentLevel, O); - } - - void onSetOptionImpl(const DagInit& D, - unsigned IndentLevel, raw_ostream& O) const { - CheckNumberOfArguments(D, 2); - - const std::string& OptName = InitPtrToString(D.getArg(0)); - const OptionDescription& OptDesc = OptDescs_.FindOption(OptName); - const Init* Value = D.getArg(1); - - if (OptDesc.isList()) { - const ListInit& List = InitPtrToList(Value); - - O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n"; - for (ListInit::const_iterator B = List.begin(), E = List.end(); - B != E; ++B) { - const Init* CurElem = *B; - if (OptDesc.isSwitchList()) - CheckBooleanConstant(CurElem); - - O.indent(IndentLevel) - << OptDesc.GenVariableName() << ".push_back(\"" - << (OptDesc.isSwitchList() ? CurElem->getAsString() - : InitPtrToString(CurElem)) - << "\");\n"; - } - } - else if (OptDesc.isSwitch()) { - CheckBooleanConstant(Value); - O.indent(IndentLevel) << OptDesc.GenVariableName() - << " = " << Value->getAsString() << ";\n"; - } - else if (OptDesc.isParameter()) { - const std::string& Str = InitPtrToString(Value); - O.indent(IndentLevel) << OptDesc.GenVariableName() - << " = \"" << Str << "\";\n"; - } - else { - throw "Can't apply 'set_option' to alias option '" + OptName + "'!"; - } - } - - void onSetSwitch(const Init* I, - unsigned IndentLevel, raw_ostream& O) const { - const std::string& OptName = InitPtrToString(I); - const OptionDescription& OptDesc = OptDescs_.FindOption(OptName); - - if (OptDesc.isSwitch()) - O.indent(IndentLevel) << OptDesc.GenVariableName() << " = true;\n"; - else - throw "set_option: -" + OptName + " is not a switch option!"; - } - - void onSetOption(const DagInit& d, - unsigned IndentLevel, raw_ostream& O) const - { - CheckNumberOfArguments(d, 1); - - // 2-argument form: (set_option "A", true), (set_option "B", "C"), - // (set_option "D", ["E", "F"]) - if (d.getNumArgs() == 2) { - const OptionDescription& OptDesc = - OptDescs_.FindOption(InitPtrToString(d.getArg(0))); - const Init* Opt2 = d.getArg(1); - - if (!OptDesc.isSwitch() || typeid(*Opt2) != typeid(StringInit)) { - this->onSetOptionImpl(d, IndentLevel, O); - return; - } - } - - // Multiple argument form: (set_option "A"), (set_option "B", "C", "D") - this->onEachArgument(d, &EmitPreprocessOptionsCallback::onSetSwitch, - IndentLevel, O); - } - -public: - - EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs) - : OptDescs_(OptDescs) - { - if (!staticMembersInitialized_) { - AddHandler("error", &EmitPreprocessOptionsCallback::onErrorDag); - AddHandler("warning", &EmitPreprocessOptionsCallback::onWarningDag); - AddHandler("unset_option", &EmitPreprocessOptionsCallback::onUnsetOption); - AddHandler("set_option", &EmitPreprocessOptionsCallback::onSetOption); - - staticMembersInitialized_ = true; - } - } - - void operator()(const Init* I, - unsigned IndentLevel, raw_ostream& O) const - { - InvokeDagInitHandler(this, I, IndentLevel, O); - } - -}; - -/// EmitPreprocessOptions - Emit the PreprocessOptions() function. -void EmitPreprocessOptions (const RecordKeeper& Records, - const OptionDescriptions& OptDecs, raw_ostream& O) -{ - O << "int PreprocessOptions () {\n"; - - const RecordVector& OptionPreprocessors = - Records.getAllDerivedDefinitions("OptionPreprocessor"); - - for (RecordVector::const_iterator B = OptionPreprocessors.begin(), - E = OptionPreprocessors.end(); B!=E; ++B) { - DagInit* Case = (*B)->getValueAsDag("preprocessor"); - EmitCaseConstructHandler(Case, Indent1, - EmitPreprocessOptionsCallback(OptDecs), - false, OptDecs, O); - } - - O << '\n'; - O.indent(Indent1) << "return 0;\n"; - O << "}\n\n"; -} - -class DoEmitPopulateLanguageMap; -typedef void (DoEmitPopulateLanguageMap::* DoEmitPopulateLanguageMapHandler) -(const DagInit& D); - -class DoEmitPopulateLanguageMap -: public HandlerTable -{ -private: - raw_ostream& O_; - -public: - - explicit DoEmitPopulateLanguageMap (raw_ostream& O) : O_(O) { - if (!staticMembersInitialized_) { - AddHandler("lang_to_suffixes", - &DoEmitPopulateLanguageMap::onLangToSuffixes); - - staticMembersInitialized_ = true; - } - } - - void operator() (Init* I) { - InvokeDagInitHandler(this, I); - } - -private: - - void onLangToSuffixes (const DagInit& d) { - CheckNumberOfArguments(d, 2); - - const std::string& Lang = InitPtrToString(d.getArg(0)); - Init* Suffixes = d.getArg(1); - - // Second argument to lang_to_suffixes is either a single string... - if (typeid(*Suffixes) == typeid(StringInit)) { - O_.indent(Indent1) << "langMap[\"" << InitPtrToString(Suffixes) - << "\"] = \"" << Lang << "\";\n"; - } - // ...or a list of strings. - else { - const ListInit& Lst = InitPtrToList(Suffixes); - assert(Lst.size() != 0); - for (ListInit::const_iterator B = Lst.begin(), E = Lst.end(); - B != E; ++B) { - O_.indent(Indent1) << "langMap[\"" << InitPtrToString(*B) - << "\"] = \"" << Lang << "\";\n"; - } - } - } - -}; - -/// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function. -void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O) -{ - O << "int PopulateLanguageMap (LanguageMap& langMap) {\n"; - - // For each LanguageMap: - const RecordVector& LangMaps = - Records.getAllDerivedDefinitions("LanguageMap"); - - // Call DoEmitPopulateLanguageMap. - for (RecordVector::const_iterator B = LangMaps.begin(), - E = LangMaps.end(); B!=E; ++B) { - ListInit* LangMap = (*B)->getValueAsListInit("map"); - std::for_each(LangMap->begin(), LangMap->end(), - DoEmitPopulateLanguageMap(O)); - } - - O << '\n'; - O.indent(Indent1) << "return 0;\n"; - O << "}\n\n"; -} - -/// EmitEdgePropertyHandlerCallback - Emits code that handles edge -/// properties. Helper function passed to EmitCaseConstructHandler() by -/// EmitEdgeClass(). -void EmitEdgePropertyHandlerCallback (const Init* i, unsigned IndentLevel, - raw_ostream& O) { - const DagInit& d = InitPtrToDag(i); - const std::string& OpName = GetOperatorName(d); - - if (OpName == "inc_weight") { - O.indent(IndentLevel) << "ret += "; - } - else if (OpName == "error") { - CheckNumberOfArguments(d, 1); - O.indent(IndentLevel) << "PrintError(\"" - << InitPtrToString(d.getArg(0)) - << "\");\n"; - O.indent(IndentLevel) << "return -1;\n"; - return; - } - else { - throw "Unknown operator in edge properties list: '" + OpName + "'!" - "\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed."; - } - - if (d.getNumArgs() > 0) - O << InitPtrToInt(d.getArg(0)) << ";\n"; - else - O << "2;\n"; - -} - -/// EmitEdgeClass - Emit a single Edge# class. -void EmitEdgeClass (unsigned N, const std::string& Target, - const DagInit& Case, const OptionDescriptions& OptDescs, - raw_ostream& O) { - - // Class constructor. - O << "class Edge" << N << ": public Edge {\n" - << "public:\n"; - O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target - << "\") {}\n\n"; - - // Function Weight(). - O.indent(Indent1) - << "int Weight(const InputLanguagesSet& InLangs) const {\n"; - O.indent(Indent2) << "unsigned ret = 0;\n"; - - // Handle the 'case' construct. - EmitCaseConstructHandler(&Case, Indent2, EmitEdgePropertyHandlerCallback, - false, OptDescs, O); - - O.indent(Indent2) << "return ret;\n"; - O.indent(Indent1) << "}\n\n};\n\n"; -} - -/// EmitEdgeClasses - Emit Edge* classes that represent graph edges. -void EmitEdgeClasses (const DagVector& EdgeVector, - const OptionDescriptions& OptDescs, - raw_ostream& O) { - int i = 0; - for (DagVector::const_iterator B = EdgeVector.begin(), - E = EdgeVector.end(); B != E; ++B) { - const DagInit& Edge = **B; - const std::string& Name = GetOperatorName(Edge); - - if (Name == "optional_edge") { - assert(IsOptionalEdge(Edge)); - const std::string& NodeB = InitPtrToString(Edge.getArg(1)); - - const DagInit& Weight = InitPtrToDag(Edge.getArg(2)); - EmitEdgeClass(i, NodeB, Weight, OptDescs, O); - } - else if (Name != "edge") { - throw "Unknown edge class: '" + Name + "'!"; - } - - ++i; - } -} - -/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph() function. -void EmitPopulateCompilationGraph (const DagVector& EdgeVector, - const ToolDescriptions& ToolDescs, - raw_ostream& O) -{ - O << "int PopulateCompilationGraph (CompilationGraph& G) {\n"; - - for (ToolDescriptions::const_iterator B = ToolDescs.begin(), - E = ToolDescs.end(); B != E; ++B) - O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n"; - - O << '\n'; - - // Insert edges. - - int i = 0; - for (DagVector::const_iterator B = EdgeVector.begin(), - E = EdgeVector.end(); B != E; ++B) { - const DagInit& Edge = **B; - const std::string& NodeA = InitPtrToString(Edge.getArg(0)); - const std::string& NodeB = InitPtrToString(Edge.getArg(1)); - - O.indent(Indent1) << "if (int ret = G.insertEdge(\"" << NodeA << "\", "; - - if (IsOptionalEdge(Edge)) - O << "new Edge" << i << "()"; - else - O << "new SimpleEdge(\"" << NodeB << "\")"; - - O << "))\n"; - O.indent(Indent2) << "return ret;\n"; - - ++i; - } - - O << '\n'; - O.indent(Indent1) << "return 0;\n"; - O << "}\n\n"; -} - -/// HookInfo - Information about the hook type and number of arguments. -struct HookInfo { - - // A hook can either have a single parameter of type std::vector, - // or NumArgs parameters of type const char*. - enum HookType { ListHook, ArgHook }; - - HookType Type; - unsigned NumArgs; - - HookInfo() : Type(ArgHook), NumArgs(1) - {} - - HookInfo(HookType T) : Type(T), NumArgs(1) - {} - - HookInfo(unsigned N) : Type(ArgHook), NumArgs(N) - {} -}; - -typedef llvm::StringMap HookInfoMap; - -/// ExtractHookNames - Extract the hook names from all instances of -/// $CALL(HookName) in the provided command line string/action. Helper -/// function used by FillInHookNames(). -class ExtractHookNames { - HookInfoMap& HookNames_; - const OptionDescriptions& OptDescs_; -public: - ExtractHookNames(HookInfoMap& HookNames, const OptionDescriptions& OptDescs) - : HookNames_(HookNames), OptDescs_(OptDescs) - {} - - void onAction (const DagInit& Dag) { - const std::string& Name = GetOperatorName(Dag); - - if (Name == "forward_transformed_value") { - CheckNumberOfArguments(Dag, 2); - const std::string& OptName = InitPtrToString(Dag.getArg(0)); - const std::string& HookName = InitPtrToString(Dag.getArg(1)); - const OptionDescription& D = - OptDescs_.FindParameterListOrParameter(OptName); - - HookNames_[HookName] = HookInfo(D.isList() ? HookInfo::ListHook - : HookInfo::ArgHook); - } - else if (Name == "append_cmd" || Name == "output_suffix") { - CheckNumberOfArguments(Dag, 1); - this->onCmdLine(InitPtrToString(Dag.getArg(0))); - } - } - - void onCmdLine(const std::string& Cmd) { - StrVector cmds; - TokenizeCmdLine(Cmd, cmds); - - for (StrVector::const_iterator B = cmds.begin(), E = cmds.end(); - B != E; ++B) { - const std::string& cmd = *B; - - if (cmd == "$CALL") { - unsigned NumArgs = 0; - CheckedIncrement(B, E, "Syntax error in $CALL invocation!"); - const std::string& HookName = *B; - - if (HookName.at(0) == ')') - throw "$CALL invoked with no arguments!"; - - while (++B != E && B->at(0) != ')') { - ++NumArgs; - } - - HookInfoMap::const_iterator H = HookNames_.find(HookName); - - if (H != HookNames_.end() && H->second.NumArgs != NumArgs && - H->second.Type != HookInfo::ArgHook) - throw "Overloading of hooks is not allowed. Overloaded hook: " - + HookName; - else - HookNames_[HookName] = HookInfo(NumArgs); - } - } - } - - void operator()(const Init* Arg) { - - // We're invoked on an action (either a dag or a dag list). - if (typeid(*Arg) == typeid(DagInit)) { - const DagInit& Dag = InitPtrToDag(Arg); - this->onAction(Dag); - return; - } - else if (typeid(*Arg) == typeid(ListInit)) { - const ListInit& List = InitPtrToList(Arg); - for (ListInit::const_iterator B = List.begin(), E = List.end(); B != E; - ++B) { - const DagInit& Dag = InitPtrToDag(*B); - this->onAction(Dag); - } - return; - } - - // We're invoked on a command line string. - this->onCmdLine(InitPtrToString(Arg)); - } - - void operator()(const Init* Statement, unsigned) { - this->operator()(Statement); - } -}; - -/// FillInHookNames - Actually extract the hook names from all command -/// line strings. Helper function used by EmitHookDeclarations(). -void FillInHookNames(const ToolDescriptions& ToolDescs, - const OptionDescriptions& OptDescs, - HookInfoMap& HookNames) -{ - // For all tool descriptions: - for (ToolDescriptions::const_iterator B = ToolDescs.begin(), - E = ToolDescs.end(); B != E; ++B) { - const ToolDescription& D = *(*B); - - // Look for 'forward_transformed_value' in 'actions'. - if (D.Actions) - WalkCase(D.Actions, Id(), ExtractHookNames(HookNames, OptDescs)); - - // Look for hook invocations in 'cmd_line'. - if (!D.CmdLine) - continue; - if (dynamic_cast(D.CmdLine)) - // This is a string. - ExtractHookNames(HookNames, OptDescs).operator()(D.CmdLine); - else - // This is a 'case' construct. - WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames, OptDescs)); - } -} - -/// EmitHookDeclarations - Parse CmdLine fields of all the tool -/// property records and emit hook function declaration for each -/// instance of $CALL(HookName). -void EmitHookDeclarations(const ToolDescriptions& ToolDescs, - const OptionDescriptions& OptDescs, raw_ostream& O) { - HookInfoMap HookNames; - - FillInHookNames(ToolDescs, OptDescs, HookNames); - if (HookNames.empty()) - return; - - for (HookInfoMap::const_iterator B = HookNames.begin(), - E = HookNames.end(); B != E; ++B) { - StringRef HookName = B->first(); - const HookInfo &Info = B->second; - - O.indent(Indent1) << "std::string " << HookName << "("; - - if (Info.Type == HookInfo::ArgHook) { - for (unsigned i = 0, j = Info.NumArgs; i < j; ++i) { - O << "const char* Arg" << i << (i+1 == j ? "" : ", "); - } - } - else { - O << "const std::vector& Arg"; - } - - O <<");\n"; - } -} - -/// EmitIncludes - Emit necessary #include directives and some -/// additional declarations. -void EmitIncludes(raw_ostream& O) { - O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n" - << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n" - << "#include \"llvm/CompilerDriver/Error.h\"\n" - << "#include \"llvm/CompilerDriver/Tool.h\"\n\n" - - << "#include \"llvm/Support/CommandLine.h\"\n" - << "#include \"llvm/Support/raw_ostream.h\"\n\n" - - << "#include \n" - << "#include \n" - << "#include \n" - << "#include \n\n" - - << "using namespace llvm;\n" - << "using namespace llvmc;\n\n" - - << "inline const char* checkCString(const char* s)\n" - << "{ return s == NULL ? \"\" : s; }\n\n"; -} - - -/// DriverData - Holds all information about the driver. -struct DriverData { - OptionDescriptions OptDescs; - ToolDescriptions ToolDescs; - DagVector Edges; - bool HasSink; -}; - -/// HasSink - Go through the list of tool descriptions and check if -/// there are any with the 'sink' property set. -bool HasSink(const ToolDescriptions& ToolDescs) { - for (ToolDescriptions::const_iterator B = ToolDescs.begin(), - E = ToolDescs.end(); B != E; ++B) - if ((*B)->isSink()) - return true; - - return false; -} - -/// CollectDriverData - Collect compilation graph edges, tool properties and -/// option properties from the parse tree. -void CollectDriverData (const RecordKeeper& Records, DriverData& Data) { - // Collect option properties. - const RecordVector& OptionLists = - Records.getAllDerivedDefinitions("OptionList"); - CollectOptionDescriptions(OptionLists, Data.OptDescs); - - // Collect tool properties. - const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool"); - CollectToolDescriptions(Tools, Data.ToolDescs); - Data.HasSink = HasSink(Data.ToolDescs); - - // Collect compilation graph edges. - const RecordVector& CompilationGraphs = - Records.getAllDerivedDefinitions("CompilationGraph"); - FillInEdgeVector(CompilationGraphs, Data.Edges); -} - -/// CheckDriverData - Perform some sanity checks on the collected data. -void CheckDriverData(DriverData& Data) { - // Filter out all tools not mentioned in the compilation graph. - FilterNotInGraph(Data.Edges, Data.ToolDescs); - - // Typecheck the compilation graph. - // TODO: use a genuine graph representation instead of a vector and check for - // multiple edges. - TypecheckGraph(Data.Edges, Data.ToolDescs); - - // Check that there are no options without side effects (specified - // only in the OptionList). - CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs); -} - -void EmitDriverCode(const DriverData& Data, - raw_ostream& O, RecordKeeper &Records) { - // Emit file header. - EmitIncludes(O); - - // Emit global option registration code. - O << "namespace llvmc {\n" - << "namespace autogenerated {\n\n"; - EmitOptionDefinitions(Data.OptDescs, Data.HasSink, O); - O << "} // End namespace autogenerated.\n" - << "} // End namespace llvmc.\n\n"; - - // Emit hook declarations. - O << "namespace hooks {\n"; - EmitHookDeclarations(Data.ToolDescs, Data.OptDescs, O); - O << "} // End namespace hooks.\n\n"; - - O << "namespace {\n\n"; - O << "using namespace llvmc::autogenerated;\n\n"; - - // Emit Tool classes. - for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(), - E = Data.ToolDescs.end(); B!=E; ++B) - EmitToolClassDefinition(*(*B), Data.OptDescs, O); - - // Emit Edge# classes. - EmitEdgeClasses(Data.Edges, Data.OptDescs, O); - - O << "} // End anonymous namespace.\n\n"; - - O << "namespace llvmc {\n"; - O << "namespace autogenerated {\n\n"; - - // Emit PreprocessOptions() function. - EmitPreprocessOptions(Records, Data.OptDescs, O); - - // Emit PopulateLanguageMap() function - // (language map maps from file extensions to language names). - EmitPopulateLanguageMap(Records, O); - - // Emit PopulateCompilationGraph() function. - EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O); - - O << "} // End namespace autogenerated.\n"; - O << "} // End namespace llvmc.\n\n"; - - // EOF -} - - -// End of anonymous namespace -} - -/// run - The back-end entry point. -void LLVMCConfigurationEmitter::run (raw_ostream &O) { - try { - DriverData Data; - - CollectDriverData(Records, Data); - CheckDriverData(Data); - - this->EmitSourceFileHeader("llvmc-based driver: auto-generated code", O); - EmitDriverCode(Data, O, Records); - - } catch (std::exception& Error) { - throw Error.what() + std::string(" - usually this means a syntax error."); - } -} diff --git a/utils/TableGen/LLVMCConfigurationEmitter.h b/utils/TableGen/LLVMCConfigurationEmitter.h deleted file mode 100644 index 0f2ff371967..00000000000 --- a/utils/TableGen/LLVMCConfigurationEmitter.h +++ /dev/null @@ -1,34 +0,0 @@ -//===- LLVMCConfigurationEmitter.cpp - Generate LLVMCC config ---*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open -// Source License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This tablegen backend is responsible for emitting LLVMCC configuration code. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_UTILS_TABLEGEN_LLVMCCONF_EMITTER_H -#define LLVM_UTILS_TABLEGEN_LLVMCCONF_EMITTER_H - -#include "TableGenBackend.h" - -namespace llvm { - - /// LLVMCConfigurationEmitter - TableGen backend that generates - /// configuration code for LLVMC. - class LLVMCConfigurationEmitter : public TableGenBackend { - RecordKeeper &Records; - public: - explicit LLVMCConfigurationEmitter(RecordKeeper &records) : - Records(records) {} - - // run - Output the asmwriter, returning true on failure. - void run(raw_ostream &o); - }; -} - -#endif //LLVM_UTILS_TABLEGEN_LLVMCCONF_EMITTER_H diff --git a/utils/TableGen/TableGen.cpp b/utils/TableGen/TableGen.cpp index 4b0f91a873b..f0607112007 100644 --- a/utils/TableGen/TableGen.cpp +++ b/utils/TableGen/TableGen.cpp @@ -30,7 +30,6 @@ #include "FastISelEmitter.h" #include "InstrInfoEmitter.h" #include "IntrinsicEmitter.h" -#include "LLVMCConfigurationEmitter.h" #include "NeonEmitter.h" #include "OptParserEmitter.h" #include "PseudoLoweringEmitter.h" @@ -81,7 +80,6 @@ enum ActionType { GenSubtarget, GenIntrinsic, GenTgtIntrinsic, - GenLLVMCConf, GenEDInfo, GenArmNeon, GenArmNeonSema, @@ -156,8 +154,6 @@ namespace { "Generate Clang AST statement nodes"), clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers", "Generate Clang Static Analyzer checkers"), - clEnumValN(GenLLVMCConf, "gen-llvmc", - "Generate LLVMC configuration library"), clEnumValN(GenEDInfo, "gen-enhanced-disassembly-info", "Generate enhanced disassembly info"), clEnumValN(GenArmNeon, "gen-arm-neon", @@ -349,9 +345,6 @@ int main(int argc, char **argv) { case GenTgtIntrinsic: IntrinsicEmitter(Records, true).run(Out.os()); break; - case GenLLVMCConf: - LLVMCConfigurationEmitter(Records).run(Out.os()); - break; case GenEDInfo: EDEmitter(Records).run(Out.os()); break; -- 2.34.1