Extracting a scalar from a vector

An individual scalar element can be extracted from a vector. LLVM provides the extractelement instruction for the same. The first operand of an extractelement instruction is a value of vector type. The second operand is an index indicating the position from which to extract the element.

The extractelement instruction looks like the following:

result = extractelement <4 x i32> %vec, i32 %idx

This can be further understood by keeping the following in mind:

  • vec is a vector
  • idx is the index at which the data to be extracted lies
  • result is of scalar type, which is i32 here

Let's take an example where we want to add all the elements of a given vector and return an integer.

Consider the following code:

#include "llvm/IR/IRBuilder.h" ...

Get LLVM Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.