-1

I am writing a simple compiler. I have written lexer and parser and it now generates assembly code from given code. Now I need to write an assembler which generates machine code. But the problem is that I want to make my compiler portable. it should run at least on major architectures. One way of doing it is writing different assemblers for each architecture, but it seems too difficult and time-consuming.

Is there a "least common denominator" for most architectures that I could work with to make my compiler portable? For instance, is it only necessary to "write one backend that produces LLVM IR instead of assembly"?

6
  • 5
    Compile to some intermediate language, and then write an interpreter or just-in-time compiler for that intermediate language on each of your target platforms. See here for some ideas. You can also use C as your compilation target and recompile using each architecture's native C compiler. Commented Apr 3, 2018 at 17:12
  • 2
    To re-emphasize Robert's suggestion which he hid in a link: the LLVM compiler framework gives you a production-grade compiler backend across many architectures. So for your compiler, you only have to write one backend that produces LLVM IR instead of assembly, and you get the rest for free. Commented Apr 3, 2018 at 17:50
  • 1
    Take a look at llvm.org Commented Apr 3, 2018 at 17:51
  • Take also a look at GCCJIT. It is a good (but less known) competitor to LLVM Commented Apr 3, 2018 at 19:36
  • 1
    I narrowed the question by asking for a "least common denominator" (and giving a plausible example of one), and wonder if the question can be reopened in its current form. Commented Jul 31, 2018 at 21:49

1 Answer 1

11

You cannot make a portable compiler (not in the sense you dream of).

You could make a compiler for a particular target machine -or language- (and that machine might even be something like LLVM or GCCJIT or Parrot which provide portability by defining some abstract model or intermediate language). It is common to compile to C (that is to choose C as your target language, leaving the burden of object code generation to the system's C compiler).

You could make a compiler with several backends (perhaps configurable at configure time, or even at run time). For example, x86-64, ARM, etc.. (and it also depends upon the target operating system and ABI). That does not make your compiler portable.

You might (or not) want to define some common (i.e. target neutral) intermediate representations in your compiler (and you could optimize with these intermediate representations).

Read the Dragon Book.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.