Example: incorporating Vector instructions into a PPE program

The sample program vmx_sample illustrates the ease with which vector instructions can be incorporated into a PPE program.

The program vmx_sample performs this processing:
  1. "typedefs" a union of an array of four ints and a vector of signed ints. This is only done so we can refer to the values in two different ways. (Vector elements can also be accessed using the SPU intrinsic, spu_extract. For more information about SPU intrinsics, see Intrinsic classes.
  2. Loads the literal value 2 into each of the four 32-bit fields of vector vConst.
  3. Loads four different integer values into the fields of vector v1.
  4. Calls the vec_add intrinsic, and the two vectors are added with the result being assigned to v2.
#include <stdio.h>

// Define a type we can look at either as an array of ints or as a vector.
typedef union {
	int iVals[4];
	vector signed int myVec;
} vecVar;

int main()
{
	vecVar v1, v2, vConst;  // define variables

	// load the literal value 2 into the 4 positions in vConst,
	vConst.myVec = (vector signed int){2, 2, 2, 2};

	// load 4 values into the 4 element of vector v1
	v1.myVec = (vector signed int){10, 20, 30, 40};

	// call vector add function
	v2.myVec = vec_add( v1.myVec, vConst.myVec );

	// see what we got!
	printf("\nResults:\nv2[0] = %d, v2[1] = %d, v2[2] = %d, v2[3] = %d\n\n",
			v2.iVals[0], v2.iVals[1], v2.iVals[2], v2.iVals[3]);

	return 0;
}

See Developing code for the Cell Broadband Engine for more information on how to run the example on the simulator.

Figure 1 shows the results of running the sample program.
Figure 1. Running the Vector/SIMD Multimedia Extension sample program
[user@bringup /]# callthru source vmx_sample > vmx_sample
[user@bringup /]# chmod +x vmx_sample
[user@bringup /]# vmx_sample

Results:
v2[0] = 12, v2[1] = 22, v2[2] = 32, v2[3] = 42

[user@bringup /]# _