Login or Register

Case Studies Right Offloading a Function Call

Cache classes reduce code changes

Caching Works Behind The Scenes In Constructor And Destructor

This article was updated on 2011-11-18 07:06:33


The example in the previous article Article 134 requires the explicit declaration of a local, the transfer from PPU memory into that local, and the write-back. Also, the method is now called on a different (local object) object using the component access operator ("."). These code changes can be reduced by using cache classes which are written in standard C++:

template <class T> struct cache
{
	inline cache(T* ptr):var(*ptr) //caching data
	{}
	inline T* operator->() {return &var;} //enables ->operator
	protected:
		T var;
};

template <class T> struct writeback_cache:cache<T>
{
	writeback_cache(T* ptr):cache<T>(ptr) {this->ptr = ptr;}
	~writeback_cache() { *ptr = cache<T>::var; } //writeback in destructor
	private:
		T* ptr;
};

Using these standard C++ class templates the offload example from Article 135 could be written as:

__offload()
{
	/*** begin cache setup ***/
	Type* tempptr = ptr; //shuffling to trick name lookup;
	writeback_cache<Type> ptr(tempptr); //ptr now hides ptr from parent scope
	/*** end cache setup ***/

	/*** Now use original unchanged code, but on cached instance ptr ***/
	ptr->func(ptrarg1,ptrarg2);//local this and __outer argument pointers
}

The first two code lines inside the Offload™ block are setup code for Offload™ (creating the cache variable which hides the original variable so that subsequent code does not have to be changed). The type of such a variable overloads all required operators to make the cache variable appear as the original variable it hides (a pointer in the example above). Note that except for the __offload keyword the code is still standard C++.

Cache classes are part of the Data Locality Library (See Article 71) which resides in the liboffload header (See Article 60).