Search code examples
llvmllvm-c++-api

llvm: How to get the label of Basic Blocks


I have written a pass to detect and print the label of basicblocks in a function, for I want to use splitBasicBlock() further. I wrote that like this:

virtual bool runOnModule(Module &M)
{
    for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
    {
        errs()<<"Function:"<<F->getName()<<"\n";
        //for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
        for (iplist<BasicBlock>::iterator iter = F->getBasicBlockList().begin();
                    iter != F->getBasicBlockList().end();
                    iter++)
        {
          BasicBlock* currBB = iter;
          errs() << "BasicBlock: "  << currBB->getName() << "\n";   
        }
    }
    return true;
}

IR file looks like this:

; <label>:63                                      ; preds = %43
  %64 = load i32* %j, align 4
  %65 = sext i32 %64 to i64
  %66 = load i8** %tempdst, align 8
  %67 = getelementptr inbounds i8* %66, i64 %65
  store i8 -1, i8* %67, align 1
  br label %73

; <label>:68                                      ; preds = %43
  %69 = load i32* %j, align 4
  %70 = sext i32 %69 to i64
  %71 = load i8** %tempdst, align 8
  %72 = getelementptr inbounds i8* %71, i64 %70
  store i8 0, i8* %72, align 1
  br label %73

; <label>:73                                      ; preds = %68, %63
  br label %74

However, I got nothing about the label:

Function:main
BasicBlock:
BasicBlock:
BasicBlock:

What's wrong with these "unnamed" basic block? What should I do?


Solution

  • Values in LLVM IR are not required to have a name; and indeed, those basic blocks don't have names, which is why you get an empty string from currBB->getName().

    The reason that they have names in the LLVM IR printout is because when you print to the textual format of LLVM IR (as it appears in .ll files), you have to assign a name to them to make them referable, so the printer assigns sequential numeric names to basic blocks (and other values). Those numeric names are only created by the printer, though, and don't actually exist in the module.