[LLVMdev] Steps to addDestination

Tim Northover t.p.northover at gmail.com
Thu Jul 25 00:28:48 PDT 2013


> Your code might look like:
>     Value *Address = emitCodeToChooseResult(Results, InsertLoc);

And a particularly silly implementation of emitCodeToChooseResults
might decide to call rand() at runtime and jump to whichever block it
decided. In that case you'd be trying to write code to produce IR
resembling:

@.blocks = private unnamed_addr constant [2 x i8*] [i8*
blockaddress(@foo, %block1), i8* blockaddress(@foo, %block2)]
declare i32 @rand()

; This whole block would actually be inside
define i32 @foo() {
   %RandomNumber = call i32 @rand()
   %ResultIndex = urem i32 %RandomNumber, 2
   %ResultBlock = getelementptr [2 x i8*]* @.blocks, i32 0, i32 %ResultIndex
   %block = load i8** %ResultBlock

   ; Code above produced by emitCodeToChooseResults, code below
produced elsewhere
   indirectbr i8* %block, [label %block1, label %block2]
block1:
   ret i32 0
block2:
   ret i32 42
}

For this, emitCodeToChooseResult would go through the stages:
1. ConstantArray::get to create the array of each blockaddress in Results.
2. Create a new GlobalVariable to store these addresses
3. Get a reference to rand() using Module->getOrInsertFunction
4. Emit calls to this RandFunction and a urem to calculate the block index.
5. Create a getelementptr instruction referring to the GlobalVariable
and the random result
6. Create a load from the address calculated.
7. Done, return this loaded value (as in "return LoadedPtr" rather
than "ReturnInst::Create(LoadedPtr, ...)").

There are obviously many other ways you could make the decision.

Cheers.

Tim.



More information about the llvm-dev mailing list