Search code examples
c++llvmllvm-clang

How to operate on LLVM Bitvectors?


(I apologize if this is straight forward, I'm not well versed in C++)

I have

#include <llvm/ADT/BitVector.h>

Looking at the defintion file, it defines

// Intersection, union, disjoint union
bitVector &operator&=(const BitVector RHS) { ... }

I want to do the union of two bit vectors; that seems to be a definition for intersection, so I'm guessing intersection would be something like this:

bitVector1 &= bitVector2;

Is this correct? Further down, it declares, without comment,

bitVector &operator|=(const bitVector &RHS) { ... }

Would it correct to assume this is the union operator? (bit operation is |=)

Thanks for the help!


Solution

  • The &= performs logical AND on the individual elements of the LHS and RHS BitVector operands and stores the result in LHS operand.

    The |= performs logical OR on the individual elements of the LHS and RHS BitVector operands and stores the result in LHS operand.

    A minimal example:

    #include <iostream>
    #include <llvm/ADT/BitVector.h>
    
    llvm::BitVector  bitVector1(10, true);
    llvm::BitVector  bitVector2(10, false);
    llvm::BitVector  bitVector3(10, true);
    
    int main()
    {
        for(int i = 0; i < bitVector1.size(); i++)
            std::cout << bitVector1[i] << ' ';
        std::cout << '\n';        
    
        bitVector2[4] = true; //5th element set to true
    
        bitVector1 &= bitVector2;
    
        for(int i = 0; i < bitVector1.size(); i++)
            std::cout << bitVector1[i] << ' ';
        std::cout << '\n';
    
    
        bitVector1 |= bitVector3;
    
    
        for(int i = 0; i < bitVector1.size(); i++)
            std::cout << bitVector1[i] << ' ';
        std::cout << '\n';        
    
    }
    

    Output:

    1 1 1 1 1 1 1 1 1 1 
    0 0 0 0 1 0 0 0 0 0 
    1 1 1 1 1 1 1 1 1 1 
    

    Live Demo