• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    625
  • comments
    1446
  • views
    1006530

Real-world garbage collection with LLVM

Sign in to follow this  
Followers 0
ApochPiQ

3254 views

The last major task for release 14 of the Epoch programming language is integrating garbage collection with the LLVM-supported JIT native code generation layer.

Ostensibly, LLVM supports hooks for making garbage collection possible. It doesn't take much digging to find out that this is a complete lie, and LLVM is actually pretty terrible at interoperating with garbage collection schemes.

First of all, you can only mark stack allocations as holding GC roots. Registers must be spilled into stack values prior to running a GC pass or you can miss roots. More annoyingly, you can only declare GC root stack allocations in the prolog of a function - you can't mark them inside, say, the body of a loop. This means you either generate a lot of excess stack reads/writes, or you do something twisted to work around the problem.

I'm proud of Epoch's runtime performance right now, so I opted to go the twisted route.

The Epoch garbage collector will now only trigger on the exit from a function or after a certain number of iterations of a closed loop (to avoid excess memory consumption in tight loop code). This means that you will never trip a garbage collection in the middle of a complex expression, which in turn limits the number of stack hits I have to perform. So that much I can suffer through.

To do accurate garbage collection, we need three things:

  • A map of all stack slots that can contain GC roots
  • A way to get this map into the GC so it can use it
  • A way to crawl the machine stack based on this map and begin mark/sweep tracing from the discovered roots
    So LLVM has a nifty @llvm.gcroot intrinsic which lets you accomplish the first goal; the code generation layer will output a stack map for you.

    Except it doesn't.

    What it does is create a stack map and then make it totally inaccessible to JIT frontends, which strikes me as more than a bit stupid. I quickly found the comment buried in the documentation suggesting that you can only access the stack map when outputting assembly language listings. WTF?! It was at this point that I started really feeling the truth that others have remarked about on the internet: LLVM just sucks for garbage collectors.

    Me being stubborn and thick-headed, though, I decided to just plow forward and hope for the best.

    I hacked around the unavailable stack map issue by implementing a custom GCStrategy class with CustomSafePoints set to true. When findCustomSafePoints() is called, I do the exact same logic as the LLVM default implementation of safe-point location, with two tweaks:

    • All safe points are cached in a location accessible to the frontend (and, later, the GC as running against the JITted code)
    • I actually implemented support for GC::Return safepoints so I can call garbage collection routines upon function exit. LLVM provides GC::Return and GC::Loop "kinds" of safepoints but then stupefyingly fails to implement support for either one.
      The next annoying omission in LLVM is the lack of a stack walking function to actually use stack maps. I suppose this can be forgiven since LLVM is not (ostensibly) in the business of target-specific stack walking code. But it's still annoying.

      Thankfully I've spent enough time doing reversing and assembly-level hacking that I'm comfortable with the idea of crawling the machine stack myself. It didn't take long to put together a function for this, although getting it to not clobber the machine state was a bit trickier.

      There are two tricks to keep in mind when doing post-function-body garbage collection invocations:

      • Back up an instruction before the RET before you CALL the garbage collector. This lets you inject the CALL prior to the POP EBP that destroys the function's stack frame and makes this whole exercise pointless.
      • Don't forget that you were about to RET from a function; write some custom prolog/epilog code to ensure you don't clobber EAX during garbage collection. Or at least save it off someplace so you can restore it once you're done clobbering it.
        Armed with a stack crawler, I found one final hurdle that is probably the most shining example of LLVM's complete lack of consideration for garbage collector authors: once you generate a safe point, you can't actually determine what machine address it's at in the emitted machine code! Derp.

        So I wound up making a minor API tweak to the ExecutionEngine class in LLVM, adding in plumbing to get to the underlying JIT engine and ask for the address of the MCSymbol corresponding to the injected GC safe point. It took some minor arithmetic to adjust the reported address to line up with actual return addresses in each stack frame, but nothing too painful.


        The results speak for themselves:

        Garbage collection experiment.png


        So as of now I have a working way to crawl the stack and look for GC roots. I'm starting out only supporting GC on strings since that's easier than dealing with all the other types in the language; but that'll come soon enough. I want to perfect the actual mark/sweep logic first and then mess with extending it to handle the whole type system.

        Next step is to go through and actually do mark/sweep and emit a list of live strings versus garbage strings. Should be entertaining.


        Overall, although I've been cursing at LLVM a lot today, it's not been too terrible. It certainly beats having to build my own machine code emission layer. Part of the reason I've stuck with it is because it does do a great job of just generating fast machine code, so I'm not totally convinced it's worth abandoning and using some other JIT engine, just for the sake of GC implementation.

        If anything, I'd rather find ways to actually contribute some useful changes to LLVM that make the whole GC song and dance a little less unpleasant for the next guy.

3
Sign in to follow this  
Followers 0


8 Comments


As of this comment, I have mark/sweep garbage collection of strings implemented and working. There's a lot of hackery and magic involved, so I need to go back through and clean it all up at some point, but it runs and passes a rudimentary test.
0

Share this comment


Link to comment

Nice. I'd like to work on a GC at some point; they're cool bits of software.

 

You should go all out and make yours generational.

0

Share this comment


Link to comment

FWIW: I looked at targeting LLVM before, and it looked like a big PITA (errm... SSA scares me...), so I mostly have just been using my own interpreters and occasional naive JIT backends... (generally using an assembler to convert generated ASM into machine code).

 

all this doesn't really make LLVM sound like happy fun time either...

0

Share this comment


Link to comment
Actually, SSA makes codegen a lot cleaner and opens up a lot of potential for optimizations. It's also pretty easy to use once you get used to the general process.

As much as I hate on LLVM's GC non-support, I actually really like it for everything else it does. Part of why the GC situation frustrates me so much is that I do like LLVM overall, and don't want to leave it.
0

Share this comment


Link to comment

the problem I think is that SSA is kind of confusing though (notably the phi operator... I know what it does but don't really understand it...).

 

 

or, at least, it seems more confusing than stack machines or non-SSA three-address register machines...

 

granted, my interpreters and JITs could be considered fairly naive vs a "real" compiler (my most recent one mostly just spits out a mix of call-threaded code and some preformed instruction sequences).

 

granted, I have also ended up raging against the SysV/AMD64 ABI as well... (my stuff supports it, but "cuts a few corners").

 

currently, my JIT uses a stack-machine model, but I had considered moving to a register machine model, just it is hard to justify the time/effort this would require. the bytecode would remain stack-based though, using a register machine mostly as the backend model (I have done this in the past though...).

0

Share this comment


Link to comment

Thanks for your feedback, that's interesting!

Have you look about the generated code? I have read many times that using llvm.gcroot is removing most of the potential optimizations later done by LLVM (the issue 1917 for example was closed with 'wontfix') so I'm not sure that LLVM allows gcroot to be promoted to registers.

0

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now