Working with alias.scope and noalias metadata in LLVM

This post briefly talks about the ScopedNoAlias alias-analysis pass in LLVM. It demonstrates the code snippets to attach, read and remove the metadata related to the ScopedNoAlias alias-analysis pass. It also talks about how the metadata is interpreted by the ScopedNoAlias alias-analysis pass.


The ScopedNoAlias alias-analysis pass in LLVM is used to determine whether a pair of pointers can alias with respect to the domains. A domain consists of multiple scopes and is defined by an id and an optional descriptive string. A scope consists of an id, a domain, and an optional descriptive string. The list of scopes can be specified using the alias.scope and noalias metadata. Metadata is essentially some additional information that is used by optimization passes. The alias.scope and noalias metadata can be attached to the load and store instructions. The ScopedNoAlias alias-analysis pass relies on the alias.scope and noalias metadata to infer the alias result for a given pair of pointers. 


alias (p1,p2) =

no-alias,

for some domain set(alias.scope) for p1 ⊆ set(noalias) for p2 or set(alias.scope) for p2 ⊆ set(noalias) for p1.


may-alias,

otherwise.

Let us now see code snippets for the creation of domains and scopes, as well as for the attachment, reading, and removal of alias.scope and noalias metadata in LLVM.


Creating a new domain


MDBuilder MDB(I->getContext());

MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain("MyDomain1");


Creating a new scope


MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, "MyScope1");


Attaching the metadata


SmallVector<Metadata *, 4> Scope;

Scope.push_back(NewScope);


//alias.scope metadata.

I->setMetadata(LLVMContext::MD_alias_scope,

MDNode::concatenate(I->getMetadata(LLVMContext::MD_alias_scope),

MDNode::get(I->getContext(), Scope)));

//noalias metadata.

I->setMetadata(LLVMContext::MD_noalias,

MDNode::concatenate(I->getMetadata(LLVMContext::MD_noalias),

MDNode::get(I->getContext(), Scope)));


Reading the metadata


//Prints alias.scope metadata found.

if(auto M = I->getMetadata(LLVMContext::MD_alias_scope)) {

for (const MDOperand &MDOp : M->operands()) {

if (const MDNode *MD = dyn_cast<MDNode>(MDOp)) {

errs() << *I << “ “ << *MD << “\n”;

}

}

}


//Prints noalias metadata found.

if(auto M = I->getMetadata(LLVMContext::MD_noalias)) {

for (const MDOperand &MDOp : M->operands()) {

if (const MDNode *MD = dyn_cast<MDNode>(MDOp)) {

errs() << *I << “ “ << *MD << “\n”;

}

}

}


Removing the metadata


//Removing alias.scope metadata.

I->setMetadata(LLVMContext::MD_alias_scope, NULL);


//Removing noalias metadata.

I->setMetadata(LLVMContext::MD_noalias, NULL);


References

  1. https://llvm.org/docs/LangRef.html#noalias-and-alias-scope-metadata

  2. https://llvm.org/doxygen/ScopedNoAliasAA_8cpp_source.html

Comments

Popular posts from this blog

Adding intrinsics to LLVM’s backend