Upgrade to Pro — share decks privately, control downloads, hide ads and more …

自作Cコンパイラのススメ

うたもく
November 23, 2018

 自作Cコンパイラのススメ

@OSC 島根 2018

うたもく

November 23, 2018
Tweet

More Decks by うたもく

Other Decks in Technology

Transcript

  1. $ίϯύΠϥ l HDD(/6 $PNQJMFS$PMMFDUJPOc$$PNQJMFS 4 Preprocessor + | v Compiler

    + | v Assembler + | v Linker cc1 ɾɾɾ as ɾɾɾ collect2
  2. $ gcc -v hello.c -o hello ⁝ /usr/lib/gcc/x86_64-linux-gnu/6/cc1 -quiet -v

    -imultiarch x86_64- linux-gnu hello.c -quiet -dumpbase hello.c -mtune=generic -march=x86- 64 -auxbase hello -version -o /tmp/ccMImyep.s ⁝ #include "..." search starts here: #include <...> search starts here: /usr/lib/gcc/x86_64-linux-gnu/6/include ⁝ as -v --64 -o /tmp/cceGWlm9.o /tmp/ccMImyep.s ⁝ /usr/lib/gcc/x86_64-linux-gnu/6/collect2 -plugin /usr/lib/gcc/x86_64- linux-gnu/6/liblto_plugin.so … -o hello … -L/usr/lib/x86_64-linux- gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/6/../../.. /tmp/cceGWlm9.o … COLLECT_GCC_OPTIONS='-v' '-o' 'hello' '-mtune=generic' '-march=x86- 64' 5
  3. $ίϯύΠϥ l HDD(/6 $PNQJMFS$PMMFDUJPOc$$PNQJMFS 6 Preprocessor + | v Compiler

    + | v Assembler + | v Linker cc1 ɾɾɾ as ɾɾɾ collect2 ࣗ࡞
  4. ࡞Δࡍͷઓུ l ֶͿ ਅࣅΔ l ͓खຊΛਅࣅ͍ͯ͘ l DD !SVJ͞Μ l

    4UFQCZ4UFQ l Ұؾʹ࡞Γ্͛Α͏ͱ͢ΔͱͭΒ͍ l ΠϯΫϦϝϯλϧͳ։ൃ l ΞηϯϒϦΛు͘·ͰͷҰ࿈ͷྲྀΕͰ։ൃ͢Δ l SDD l DDͷϑΝʔετίϛοτ͔Β͢΂ͯ3VTUͰॻ͖׵͑Δ 9
  5. ੒௕աఔ ॳظ use std::env; fn main() { let mut args

    = env::args(); if args.len() != 2 { eprint!("Usage: 9cc <code>¥n"); return; } print!(".intel_syntax noprefix¥n"); print!(".global main¥n"); print!("main:¥n"); print!(" mov rax, {}¥n", args.nth(1).unwrap()); print!(" ret¥n"); return; } 10     %rax 
  6. ੒௕աఔ ݱࡏ l ࢛ଇԋࢉ ࿦ཧԋࢉ   l ϩʔΧϧม਺ άϩʔόϧม਺

    l GPSXIJMF l ؔ਺ݺͼग़͠ ؔ਺ఆٛ l DIBSJOU จࣈྻϦςϥϧ l ϙΠϯλ ഑ྻ l ߏ଄ମ l FYUFSOJODMVEFEFGJOF@@-*/&@@ l ίϝϯτจ 11
  7. 12 int fibdp[100]; int fib(int n) { if (n ==

    0 || n == 1) { return n; } else if (fibdp[n] != 0) { return fibdp[n]; } else { fibdp[n] = fib(n-2) + fib(n-1); return fibdp[n]; } } int main() { for (int i = 0; i < 100; i++) fibdp[i] = 0; int ans = fib(46); printf("%d¥n", ans); return 0; }  int prime(int n) { if (n % 2 == 0) return 0; int k = 3; while (k * k <= n) { if (n % k == 0) return 0; k = k + 2; } return 1; } int main() { int i = 2; while (i < 10000) { if (prime(i)) printf("prime!: %d¥n", i); i++; } return 0; } 
  8. ಘΕͨྗ ! ! ίʔσΟϯά l ೖྗม׵ͯ͠ҧ͏ܗͷ΋ͷΛు͘ ! $ݴޠ l ࢓༷

    ! ௿Ϩϕϧϓϩάϥϛϯά l Yͷ֤छϨδελͷѻ͍ l ΞηϯϒϦݴޠ ! ελοΫ l ϩʔΧϧม਺ͷѻ͍ 13
  9. ࢀߟจݙ l ௿ϨΠϠΛ஌Γ͍ͨਓͷͨΊͷ$ίϯύΠϥ࡞੒ೖ໳ IUUQTXXXTJHCVTJOGPDPNQJMFSCPPL l   ೔ͰͰ͖Δʂ $ίϯύΠϥࣗ࡞ೖ໳ IUUQTEPDTHPPHMFDPNQSFTFOUBUJPOEQJ%H

    l TFDDBNQͰηϧϑϗετ$ίϯύΠϥΛͭͬͨ͘ IUUQTTQFBLFSEFDLDPNBORPVTFDDBNQEFTF l ࣗ࡞$ίϯύΠϥͰ ,FO5IPNQTPOͷϩάΠϯϋοΫ Λ࠶ݱͯ͠Έͨ IUUQYGIBUFOBCMPHDPNFOUSZ l ਓͰ͕Μ͹Δࣗ࡞$ίϯύΠϥ IUUQTXXXVUBNLKQCMPHSDD 15
  10. 18