Disabling optimizations in clang/llvm for specified regions in code

I wanted to inquire if there is a way within LLVM/Clang to limit (function-level) optimizations to certain contiguous regions within the function. E.g.

void foo(int* A, int n1, int n2){

// Enable optimizations above this loop

// (#pragma clang loop nolicm?)

for(int i = 0; i < n1; ++i){

for(int j=0; j< n2; j++){

int i_offset = (n2*i); // Do not Hoist to outside current loop

int net_offset = i_offset + j;

A[net_offset] = …;



// Enable optimizations below this loop


In the above case, would it be possible to disable Loop Invariant Code motion just for that loop nest in the function foo, but enable it to be used elsewhere in the function? We would like to disable certain passes like LICM for our use-case (We’ve defined markers inside the functions specifying the start and end of certain regions and we want to limit certain optimizations as we will be extracting those code regions later on).

The clang pragma at https://bcain-llvm.readthedocs.io/projects/clang/en/latest/LanguageExtensions/#id20 acts at a per function level. Similarly the loop optimizations pragmas https://clang.llvm.org/docs/LanguageExtensions.html#id30 only cover some of the loop specific metadata’s available in LLVM (For example, I wasn’t able to find a way to add ‘llvm.licm.disable’ to loops at the source level).

Thank you,

Abdul Rafae Noor

Grad Student,

University of Illinois, Urbana Champaign

llvm.licm.disable would need to be exposed via a pragma. If you would
like to contribute a patch doing that, look for the LoopHint attribute
and into CGLoopInfo.cpp. The consistent syntax would be `#pragma clang
loop licm(disable)`. Note that the GVN pass also does some kind of
invariant code motion.

However, I think the more robust approach would be we extract the loop
into a different function and disable some optimizations in the
functions via function attributes, such as optnone or "target-cpu"
which would be set via a Clang equivalent to `#pragma GCC
optimize("...")`, such as `#pragma clang optimize("-fno-licm")`. This
is because metadata can get lost during some passes while function
attributes are not forgotten that easily. Neither "#pragma clang
optimize" nor "-fno-licm" currently exist, but at least the former is
a frequently requested feature.


I don’t think there is currently any way to disable an arbitrary transformation for an arbitrary block of code, it may be possible to implement something like that though.

You may be able to mark variables volatile to prevent certain transformations for those variables.

Another way is to insert something like this before and after a block of code to prevent optimizations.

asm volatile(“” : : : “memory”);