Skip to content

Instantly share code, notes, and snippets.

@zsrkmyn
Created July 23, 2021 07:15
Show Gist options
  • Save zsrkmyn/d6cce178a37c7d8eb7805b8aa13ecedf to your computer and use it in GitHub Desktop.
Save zsrkmyn/d6cce178a37c7d8eb7805b8aa13ecedf to your computer and use it in GitHub Desktop.
Insert a printf into LLVM IR for debug purpose
static void insertPrint(BasicBlock *BB, StringRef S) {
Module *M = BB->getModule();
LLVMContext &Ctx = M->getContext();
auto *CharPointerTy = PointerType::get(IntegerType::getInt8Ty(Ctx), 0);
auto *PrintfTy =
FunctionType::get(IntegerType::getInt32Ty(Ctx), {CharPointerTy}, true);
auto Printf = M->getOrInsertFunction("printf", PrintfTy);
auto Arr = ConstantDataArray::getString(Ctx, S);
GlobalVariable *GV = new GlobalVariable(
*M, Arr->getType(), true, GlobalValue::PrivateLinkage, Arr, ".str");
GV->setAlignment(MaybeAlign(1));
CallInst::Create(Printf, {ConstantExpr::getBitCast(GV, CharPointerTy)}, "",
BB);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment