arrow_back_ios Back to List

Cache classes reduce code changes

Offload KB - case-studies

Old Content Alert

Please note that this is a old document archive and the will most likely be out-dated or superseded by various other products and is purely here for historical purposes.

The example in the previous article /kb/134.html 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 /kb/135.html 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 /kb/71.html) which resides in the liboffload header (See /kb/60).html.

Share