4584l3.txt

Listing 3. An Example of AltiVec-enabled gcc Use

/* vecdemo1.c */
#include <stdio.h>

#define CHARS_IN_VEC		( 16 )
#define SHORTS_IN_VEC	( 8 )
#define INTS_IN_VEC		( 4 )
#define FLOATS_IN_VEC	( 4 )

/*
 * Unions provide a convenient mechanism for 
 * ensuring your vector data is aligned 
 * on 128-bit boundaries (required) 
 * and for accessing individual elements 
 * of a vector.
 */
typedef union
{
	char c[ CHARS_IN_VEC ];
	vector unsigned char vchar;
} charToVec;
typedef union
{
	short shrt[ SHORTS_IN_VEC ];
	vector signed short vshort;
} shortToVec;

typedef union
{
	int i[ INTS_IN_VEC ];
	vector signed int vint;
} intToVec;

typedef union
{
	float flt[ FLOATS_IN_VEC ];
	vector float vfloat;
} floatToVec;

int main ( int argc, char ** argv )
{

	int i;

	/*********************************/
	/* Declare/define some constants */
	/*********************************/
	vector unsigned char cVals = (vector unsigned
char)('G','o','o','d','b', 'y', 'e',' ','W','o','r','l','d','!','
','\0' );
	vector signed short sVals = ( vector signed short ) \
		(0x0a00,0x0a01,0x0a02,0x0a03,0x0a04,0x0a05,0x0a06,0x0a07);
	vector signed int iVals = ( vector signed int ) (3,4,5,6);
	vector float fVals = ( vector float ) (3.0, 4.0, 5.0, 6.0 );

	/*
	 * Declare some vector types for 
	 * vector processing (SIMD)
	 */
	shortToVec sIn, sOut;
	intToVec iIn, iOut;
	floatToVec fIn, fOut;

#ifdef __VEC__
	printf( "AltiVec aware compiler\n\n" );
#endif

	/* Initialize the short vector to some value */
	for( i = 0; i < SHORTS_IN_VEC; i++ )
		sIn.shrt[i] = i;
	
	/*
	 * Perform an SIMD add of the constant vector 
	 * and the variable vector
	 */
	sOut.vshort = vec_add( sVals, sIn.vshort );

	/* Display the results */
	printf( "vector short values after vec_add()\n" );
	for( i = 0; i < SHORTS_IN_VEC; i++ )
	{
		printf( "0x%x ", sOut.shrt[i] );
	}
	printf( "\n\n" );

	/* Initialize the int vector to some value */
	for( i = 0; i < INTS_IN_VEC; i++ )
		iIn.i[i] = i;

	/*
	 * Perform an SIMD add of the constant vector 
	 * and the variable vector
	 */
	iOut.vint = vec_add( iVals, iIn.vint );

	/* Display the results */
	printf( "vector int values after vec_add()\n" );
	for( i = 0; i < INTS_IN_VEC; i++ )
		printf( "%d ", iOut.i[i] );
	printf( "\n\n" );

	/* Initialize the float vector to some value */
	for( i = 0; i < 4; i++ )
		fIn.flt[i] = (float)i;
	
	/*
	 * Perform an SIMD add of the constant vector 
	 * and the variable vector
	 */
	fOut.vfloat = vec_add( fVals, fIn.vfloat );

	/* Display the results */
	printf( "vector float values after vec_add()\n" );
	for( i = 0; i < FLOATS_IN_VEC; i++ )
		printf( "%f ", fOut.flt[i] );
	printf( "\n\n" );
	
	printf( "%s\n", &cVals );

	return ( 0 );
}

