-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"?

maple_shaft
  • 26,570

1 Answers1

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.