Login
Username:

Password:

Remember me



Lost Password?

Register now!

Sections

Who's Online
168 user(s) are online (106 user(s) are browsing Forums)

Members: 0
Guests: 168

more...

Support us!

Headlines

 
  Register To Post  

« 1 2 3 4 (5)
Re: A1222 support in the SDK and problems
Just popping in
Just popping in


See User information
@all

Here a variant fo the binutils using

ALIGNMENT=64
PAGE_SIZE
=0x1000


Using the stream as example I cannot find any difference in output of the binaries. But maybe this just a coincide, because of the nature of stream source.

Go to top
Re: A1222 support in the SDK and problems
Just can't stay away
Just can't stay away


See User information
As the .ctors and .dtors sections themselves don't need more than 4-byte/32-bit alignment wouldn't it make more sense to move them to the end of the segment?

Also do they really need to be writable?

Go to top
Re: A1222 support in the SDK and problems
Just popping in
Just popping in


See User information
@salass00

The .ctors/.dtors section are on in the beginning to have the same output of the linking process like the "old" binutils.

If we move them to the end it the same order of sections like the default elf script from binutils.

@jeorg

To force the alignment of section might not make sense on amigaos, because the elf loader allocates memory
in the real address space, which must be correctly align. And does the elf.library take that into consideration?

Go to top
Re: A1222 support in the SDK and problems
Just popping in
Just popping in


See User information
This Taborizing link was dead

Taborizing Drivers & Libraries (a.k.a., Optimizing Code for the e500 SPE)
https://keasigmadelta.com/blog/taboriz ... imizing-for-the-e500-spe/

so i put here (If Hans agrees; otherwise, I'll delete it.)


Introduction

A1222 (codenamed Tabor). It's a nice little board; one that I'm planning to out of.
Anyway, the P1022 CPU on-board has a peculiarity: it's got a Stream Processing Engine (SPE) for floating-point calculations that's incompatible with the standard PowerPC FPU.
While there will be a fast FPU emulator that uses the SPE, for some code it's worth compiling an SPE native version.
In particular, the graphics drivers I've written use the FPU (and/or altivec) to copy data to/from graphics memory.
That's performance critical, and so should be optimized for the SPE (a.k.a., "Taborized"). Taborizing libraries isn't as straightforward as it sounds, and I encountered some challenges.
To save you the time, here's everything you need to know if you have libraries you want to Taborize.


Compiling for the SPE

You'll need a version of GCC that supports the SPE. That is a version between 5 and 7, inclusive (they removed SPE support in newer versions).
After that, it's a simple matter of setting the right command line options:
1 -mspe -mcpu=8540 -mfloat-gprs=double -mabi=spe

These will compile code for the SPE. Additionally, Daniel Müßener () has given some extra parameters to avoid some compiler bugs (GCC 5.4.0 generated code causing structure element alignment issues):
1 -fno-inline-functions -fno-partial-inlining -fno-align-functions -fno-align-jumps -fno-align-loops -f

NOTE: This may or may not be necessary with the latest GCC. I'm publishing it just in case.


Compile Just the Critical Bits for the SPE

Recompiling the whole library for SPE sounds like the easiest solution.
However, you probably can't because the Application Binary Interface (ABI) is different.
PowerPC processors pass floating-point parameters to functions via the floating-point registers.
Well, those registers don't exist on the P1022 (e500 core).
Therefore, if your library/driver has public functions with floats/doubles, then compiling the entire library for the SPE would make it incompatible with regular code.
So compile just the critical bits for the SPE, and make sure that all functions called from external code (i.e., is part of the library's/device's API) is compiled for the regular PowerPC.
Often it's unnecessary to recompile the whole thing, anyway.
In the W3D_SI driver's case, only the code generating vertices and writing them to VRAM needed optimizing, and it was already set up to use altivec optimized code on machines with altivec.
So, just that code was compiled for the SPE.
There was also no need for a separate SPE version of the driver, because the SPE optimized code sits nicely alongside the regular FPU and altivec code.


Forcing Correct Stack alignment

Just when you thought you were done, a complication.
Code generated for the SPE assumes that the stack is 16-byte aligned. Indeed, the says it should be so for all PowerPC code.
Well, some programs don't respect this (e.g., OpenArena).
While regular PowerPC code doesn't mind, the SPE has instructions requiring an 8-byte alignment.
And, yes, GCC uses those instructions in the function's prolog. So, when something like OpenArena misaligns the stack, it's "game over, man!"
The only solution is to force the stack to be correctly aligned when calling SPE code.
GCC has an option to force stack alignment... but it's for x86/x64 only There's nothing for PowerPC.
So, I've written a tool that will patch the generated assembly code...


PatchForSPE – A Tool To Realign the Stack

This tool takes assembly code generated by GCC, and then patches the function prologs/epilogues to realign the stack.
You use it as follows:
• Download it:
• Either compile it separately, or add a rule to your makefile. For example:
1 PatchForSPE: PatchForSPE.cpp
2 $(CXX) -o $@ $<

• Add the following to CFLAGS_SPE (needed for the pacher to work):
1 -mno-regnames
• Generate assembly code instead of the output binary, with the -S option, and run it through PatchForSPE (hint use -ggdb instead of -gstabs for debug info, or the GNU assembler might give warnings). An example makefile rule:
1 $(CC) $File_spe.S: File.c File.h PatchForSPE
2 $(CC) -c $(CFLAGS) $(CFLAGS_SPE) -S -o $@_in $<
3 PatchForSPE $@_in $@

• Finally, compile the assembly file to an object file:
1 File_spe.o: $(CFG)/File_spe.S
2 $(CC) -c $(CFLAGS) $(CFLAGS_SPE) -o $@ $<

NOTE: These instructions are in PatchForSPE.cpp too.


How’s the Performance

I'm a little hesitant about publishing benchmarks, because I'm still using the old exception-based pure software FPU emulator.
So, the performance boost will NOT be comparable to the fast FPU emulator that's coming.
Nevertheless, here's some data:
Program SPE NativeOld W3D_SI (fps) Taborized W3D_SI (fps)
Cow3d (no info bar) No 12 ~144

Wings Remastered
- Bombing Yes 55 240-270
- Strafing 12 95-120

VoxelBird (medium detail) Yes <16 ~60

VoxelNoid (no shadows) Yes ~30 ~70

IMPORTANT: The comparison is between an SPE optimized W3D_SI, and the old version running via the old slow exception-based FPU emulator.
Final performance with the fast FPU emulator may be different.
Wings, VoxelBird and VoxelNoid were all compiled for the SPE in these tests, so those tests show near fully native SPE performance.
Performance is similar to a Sam460ex with the same graphics card.


Summary

In brief, to optimize a library for running on the Tabor/A1222:
1. A version of GCC that supports the SPE (version 5.4.0 or newer should work, up to GCC v6.X)
2. Only compile bits for SPE that need optimizing (i.e., use the FPU a lot and are performance critical).
Functions that have float/double parameters and are part of the library's API should NOT be compiled for the SPE (for compatibility with generic PowerPC code)
3. Use the PatchForSPE tool to force stack realignment before SPE code is executed
I hope this information is useful. If you discover anything new related to "Taborizing" code, then leave a comment below.

Go to top
Re: A1222 support in the SDK and problems
Just popping in
Just popping in


See User information
Source code: PatchForSPe.cpp

/** PatchForSPE.cpp
 *
 * Patches assembly code generated for the e500 Stream Processing Engine
 * to align the stack to 16 bytes (some naughty code misaligns the stack).
 *
 * How to use:
 * - Either compile this with G++ -o PatchForSPE.exe PatchForSPE.cpp, or add
 *   a rule to your makefile:
 *   PatchForSPE: PatchForSPE.cpp
 *       $(CXX) -o $@ $<
 * - Generate assembly code instead of the output binary, with the -S option,
 *   and run PatchForSPE on it (hint use -ggdb instead of -gstabs for debug 
 *   info, or the GNU assembler might give warnings). 
 *   An example makefile rule:
 *      $(CC) $File_spe.S: File.c File.h PatchForSPE
 *      $(CC) -c $(CFLAGS) $(CFLAGS_SPE) -S -o $@_in $< 
 *      PatchForSPE $@_in $@
 * - Then, compile the assembly file to an object file:
 *  File_spe.o: $(CFG)/File_spe.S
 *      $(CC) -c $(CFLAGS) $(CFLAGS_SPE) -o $@ $<
 *
 * CFLAGS_SPE should contain the following to generate SPE code:
 *    -mspe -mcpu=8540 -mfloat-gprs=double -mabi=spe -mno-regnames
 * 
 * My full CFLAGS_SPE is:
 *    -mspe -mcpu=8540 -mfloat-gprs=double -mabi=spe  -DUSE_SPE \
 *    -fno-inline-functions -fno-partial-inlining -fno-align-functions \
 *    -fno-align-jumps -fno-align-loops -fno-align-labels \
 *    -fno-inline-small-functions -fno-indirect-inlining -mno-regnames
 * 
 * I use these flags with GCC 5.5.0, so some of them may no longer be 
 * necessary when using a newer version of GCC.
 * 
 * IMPORTANT: Support for SPE was removed from GCC. You'll need a GCC version
 * from v5 to v7 when compiling for SPE. 
 *
 * @author Hans de Ruiter
 *
 * @Copyright (C) 2018-2023 by Kea Sigma Delta Limited, all rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <fstream>
#include <sstream>
#include <string> 
#include <cstring>
#include <algorithm>


#define DEBUG


using namespace std;

// ----- CONSTANTS -----
#define NUMARGS 2 // Need 2 parameters

// ----- PRIVATE FUNCTIONS -----

static void printUsage(const char *progName) {
    
cout << progName << ": Patches GCC generated assembly for the e500 core's SPE to force 16 byte stack alignment" << endl << endl;
    
cout << "Usage: " << endl;
    
cout << progName << " <input filename> <output name>" << endl;
    
cout << "This will patch function prologs/epilogues to enforce 16 byte stack alignment. Some naughty PowerPC code" << endl
         
<< "misaligns the stack, causing code compiled for the e500 core's SPE to crash with an alignment exception. " << endl
         
<< "This will add code to make sure it's aligned correctly." << endl
         
<< endl
         
<< "Use this when writing library code that may be called from general PowerPC code (i.e., code compiled for " << endl
         
<< "plain PowerPC." << endl 
         
<< endl;
    
cout << "Example:" << endl;
    
cout << progName << " main.s_in main.s" << endl;
}

inline void assertFileGood(ifstream &file) {
    if(
file.bad()) {            
        
cout << "ERROR: Could not read the file." << endl;
        
cout <<    "Failed." << endl;
        exit(
10);
    }                        
}
// ----- FUNCTIONS -----

int main(int argc, char **argv) {
    
// Parse args
    
if(argc != NUMARGS + 1) {
        
printUsage(argv[0]);
        return 
10;
    }
    
char *inFileName = argv[1];
    
char *outFileName = argv[2];
    
ifstream inFile(inFileName);

#ifdef DEBUG    
    
cout << argv[0] << ": " << endl;
#endif
    
    
if(inFile.fail()) {
        
cout << "Could not open " << inFileName << endl;
        
cout << "Operation failed." << endl;
        return 
10;
    }

    
ofstream outFile(outFileName);
    if(
outFile.fail()) {
        
cout << "Could not open " << outFileName << "for writing." << endl;
        
cout << "Operation failed." << endl;
        return 
10;
    }
    
    
// Scan through the file
    
std::string buffer;
    const 
std::string prologStackStr("stwu 1,");
    while(!
inFile.eof()) {
        
assertFileGood(inFile);
        
std::getline(inFile, buffer);

        
// Is this line one we need to modify?
        
size_t loc;
        if((
loc = buffer.find(prologStackStr)) != std::string::npos) {
            
// Found a function's prolog. Replace the stack frame allocation code
            
loc += prologStackStr.size();
            
std::istringstream inStr(buffer);
            
inStr.seekg(loc, std::ios_base::beg);
            
int frameOffset;
            
inStr >> frameOffset;

            
outFile << "    rlwinm 12, 1, 0, 0, 27 # r3 = r1 & ~0xF (calc aligned stack pointer)" << endl
                    
<< "    stwu 1, " << frameOffset << "(12) # write r1 to address r12 - n (so, relative to aligned stack pointer)" << endl
                    
<< "    mr 1, 12 # move new aligned stack pointer into r1" << endl;
        } else if((
loc = buffer.find("addi 1,1")) != std::string::npos) {
            
// Found the stack frame deallocation code in the epilogue. Yes, it
            // needs replacing too (because it uses a static offset instead of the
            // frame pointer)
            
outFile << "    lwz 1, 0(1)" << endl;
        } else {
            
outFile << buffer << endl;
        }
    }
    
    
inFile.close();
    
outFile.close();
    
    
// All done
#ifdef DEBUG
    
cout << "Success." << endl;
#endif
}



/** A compare function for case insensitive string comparison
 */
bool caseInsensitive_compare(char ch1, char ch2)
{
    return 
toupper((unsigned char)ch1) == toupper((unsigned char)ch2);
}

/** Strips the white-space from the front and end of a string
 */
void stripWhiteSpace(string &str)
{
#ifdef DEBUG
    
cout << __func__ << " called." << endl;
#endif
    
size_t strsize = str.size();
    if(
str[0] == ' ' || str[0] == '\t')
    {
        
size_t n = 0;
        while((
str[n] == ' ' || str[n] == '\t') && n < strsize)
        {
            ++
n;
        }
        
str.erase(0, n);
    }
    
    
size_t pos = str.size() - 1;
    if(
str[pos] == ' ' || str[pos] == '\t')
    {
        while((
str[pos] == ' ' || str[pos] == '\t') && pos >= 0)
        {
            --
pos;
        }
        ++
pos;
        
str.erase(pos);
    }
}

bool getLayout(ifstream &file, const char *layoutName, string &actualLayoutName, streampos &startPos, streampos &endPos)
{
#ifdef DEBUG
    
cout << __func__ << " called with layoutName: " << (layoutName ? layoutName : "(anything)") << ", startPos:" << startPos << "and endPos:" << endPos << "." << endl;
#endif

    
streampos localStartPos = file.tellg();
    
string buffer;
    
string layoutNameStr;
    
    if(
layoutName)
    {
        
layoutNameStr = layoutName;
    }
    
    
file.clear(); // need to do this or the end-of-file check will fail
    
    
while(!file.eof())
    {
        
assertFileGood(file);
        
std::getline(file, buffer);
#ifdef DEBUG
    
cout << "read line:" << buffer << endl;
#endif
        
size_t pos = buffer.find("LABEL");
        if(
pos == 0)
        {
            
// Have a kickstart label, check if it matches
            
actualLayoutName = buffer.substr(sizeof("LABEL ") - 1);
            
stripWhiteSpace(actualLayoutName);
            if(!
layoutName || std::equal(actualLayoutName.begin(), actualLayoutName.end(), layoutNameStr.begin(), caseInsensitive_compare) == true)
            {
                
// Found the desired kickstart layout, now find the end
                
while(!file.eof())
                {
                    
assertFileGood(file);
                    
startPos = localStartPos;
                    
endPos = file.tellg();
                    
std::getline(file, buffer);
                    if(
buffer.size() == 0)
                    {
                        
// found it
                        
return true;
                    }
                }
                
file.clear(); // need to do this or the end-of-file check will fail
                
return true;
            }
        }
        
localStartPos = file.tellg();
    }
    
    return 
false;
}

bool findModule(ifstream &file, const char *moduleName, streampos startPos, streampos endPos)
{
#ifdef DEBUG
    
cout << __func__ << " called with moduleName: " << (moduleName ? moduleName : "(anything)") << ", startPos:" << startPos << "and endPos:" << endPos << "." << endl;
#endif

    
file.clear();
    
file.seekg(startPos);
    
streampos currPos = file.tellg();
    
string buffer;
    
string targetModuleName;
    if(
moduleName)
    {
        
targetModuleName = moduleName;
    }
    
    while(
currPos < endPos && !file.eof())
    {
        
assertFileGood(file);
        
std::getline(file, buffer);
#ifdef DEBUG
    
cout << "read line:" << buffer << endl;
#endif
        
size_t pos = buffer.find("MODULE");
        if(
pos == 0)
        {
            
// Have a kickstart label, check if it matches
            
string actualModuleName = buffer.substr(sizeof("MODULE ") - 1);
            
stripWhiteSpace(actualModuleName);
            if(!
moduleName || std::equal(actualModuleName.begin(), actualModuleName.end(), targetModuleName.begin(), caseInsensitive_compare) == true)
            {
                
// found it
                
return true;
            }
        }
        
startPos = file.tellg();
    }
    
    
file.clear();
    return 
false;
}

Go to top

  Register To Post
« 1 2 3 4 (5)

 




Currently Active Users Viewing This Thread: 1 ( 0 members and 1 Anonymous Users )




Powered by XOOPS 2.0 © 2001-2024 The XOOPS Project