summaryrefslogtreecommitdiffstats
path: root/library/preprocessor.cpp
blob: 31614f32949a7c18f0e4f19e4fb9c9b8b1d07b65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
 * This is ported from Preprocessor.php for performance.
 */

// #include <Winsock2.h>
#include <arpa/inet.h>
#include <algorithm>
#include <fstream>
#include <map>
#include <queue>
#include <string>
#include <vector>

/**
 * Fileformat version. Embedded in the output for parsers to use.
 */
#define FILE_FORMAT_VERSION 7

// NR_FORMAT = 'V' - unsigned long 32 bit little endian

/**
 * Size, in bytes, of the above number format
 */
#define NR_SIZE 4

/**
 * String name of main function
 */
#define ENTRY_POINT "{main}"

struct ProxyData
{
    ProxyData(int _calledIndex, int _lnr, int _cost) :
        calledIndex(_calledIndex), lnr(_lnr), cost(_cost)
    {}

    int calledIndex;
    int lnr;
    int cost;
};

struct CallData
{
    CallData(int _functionNr, int _line) :
        functionNr(_functionNr), line(_line), callCount(0), summedCallCost(0)
    {}

    int functionNr;
    int line;
    int callCount;
    int summedCallCost;
};

inline CallData& insertGetOrderedMap(int functionNr, int line, std::map<int, size_t>& keyMap, std::vector<CallData>& data)
{
    int key = functionNr ^ (line << 16) ^ (line >> 16);
    std::map<int, size_t>::iterator kmItr = keyMap.find(key);
    if (kmItr != keyMap.end()) {
        return data[kmItr->second];
    }
    keyMap[key] = data.size();
    data.push_back(CallData(functionNr, line));
    return data.back();
}

struct FunctionData
{
    FunctionData(const std::string& _filename, int _line, int _cost) :
        filename(_filename),
        line(_line),
        invocationCount(1),
        summedSelfCost(_cost),
        summedInclusiveCost(_cost)
    {}

    std::string filename;
    int line;
    int invocationCount;
    int summedSelfCost;
    int summedInclusiveCost;
    std::vector<CallData> calledFromInformation;
    std::vector<CallData> subCallInformation;

    CallData& getCalledFromData(int _functionNr, int _line)
    {
        return insertGetOrderedMap(_functionNr, _line, calledFromMap, calledFromInformation);
    }

    CallData& getSubCallData(int _functionNr, int _line)
    {
        return insertGetOrderedMap(_functionNr, _line, subCallMap, subCallInformation);
    }

private:
    std::map<int, size_t> calledFromMap;
    std::map<int, size_t> subCallMap;
};

class Webgrind_Preprocessor
{
public:

    /**
     * Extract information from inFile and store in preprocessed form in outFile
     *
     * @param inFile Callgrind file to read
     * @param outFile File to write preprocessed data to
     * @param proxyFunctions Functions to skip, treated as proxies
     */
    void parse(const char* inFile, const char* outFile, std::vector<std::string>& proxyFunctions)
    {
        std::ifstream in(inFile);
        std::ofstream out(outFile, std::ios::out | std::ios::binary | std::ios::trunc);

        std::map< int, std::queue<ProxyData> > proxyQueue;
        int nextFuncNr = 0;
        std::map<std::string, int> functionNames;
        std::vector<FunctionData> functions;
        std::vector<std::string> headers;

        std::string line;
        std::string buffer;
        int lnr;
        int cost;
        int index;

        // Read information into memory
        while (std::getline(in, line)) {
            if (line.compare(0, 3, "fl=") == 0) {
                // Found invocation of function. Read function name
                std::string function;
                std::getline(in, function);
                function.erase(0, 3);
                getCompressedName(function, false);
                // Special case for ENTRY_POINT - it contains summary header
                if (function == ENTRY_POINT) {
                    std::getline(in, buffer);
                    std::getline(in, buffer);
                    headers.push_back(buffer);
                    std::getline(in, buffer);
                }
                // Cost line
                in >> lnr >> cost;
                std::getline(in, buffer);

                std::map<std::string, int>::const_iterator fnItr = functionNames.find(function);
                if (fnItr == functionNames.end()) {
                    index = nextFuncNr++;
                    functionNames[function] = index;
                    if (std::binary_search(proxyFunctions.begin(), proxyFunctions.end(), function)) {
                        proxyQueue[index];
                    }
                    line.erase(0, 3);
                    getCompressedName(line, true);
                    functions.push_back(FunctionData(line, lnr, cost));
                } else {
                    index = fnItr->second;
                    FunctionData& funcData = functions[index];
                    funcData.invocationCount++;
                    funcData.summedSelfCost += cost;
                    funcData.summedInclusiveCost += cost;
                }
            } else if (line.compare(0, 4, "cfn=") == 0) {
                // Found call to function. ($function/$index should contain function call originates from)
                line.erase(0, 4);
                getCompressedName(line, false); // calledFunctionName
                // Skip call line
                std::getline(in, buffer);
                // Cost line
                in >> lnr >> cost;
                std::getline(in, buffer);

                int calledIndex = functionNames[line];

                // Current function is a proxy -> skip
                std::map< int, std::queue<ProxyData> >::iterator pqItr = proxyQueue.find(index);
                if (pqItr != proxyQueue.end()) {
                    pqItr->second.push(ProxyData(calledIndex, lnr, cost));
                    continue;
                }

                // Called a proxy
                pqItr = proxyQueue.find(calledIndex);
                if (pqItr != proxyQueue.end()) {
                    ProxyData& data = pqItr->second.front();
                    calledIndex = data.calledIndex;
                    lnr = data.lnr;
                    cost = data.cost;
                    pqItr->second.pop();
                }

                functions[index].summedInclusiveCost += cost;

                CallData& calledFromData = functions[calledIndex].getCalledFromData(index, lnr);

                calledFromData.callCount++;
                calledFromData.summedCallCost += cost;

                CallData& subCallData = functions[index].getSubCallData(calledIndex, lnr);

                subCallData.callCount++;
                subCallData.summedCallCost += cost;

            } else if (line.find(": ") != std::string::npos) {
                // Found header
                headers.push_back(line);
            }
        }
        in.close();

        std::vector<std::string> reFunctionNames(functionNames.size());
        for (std::map<std::string, int>::const_iterator fnItr = functionNames.begin();
             fnItr != functionNames.end(); ++fnItr) {
            reFunctionNames[fnItr->second] = fnItr->first;
        }

        // Write output
        std::vector<uint32_t> writeBuff;
        writeBuff.push_back(FILE_FORMAT_VERSION);
        writeBuff.push_back(0);
        writeBuff.push_back(functions.size());
        writeBuffer(out, writeBuff);
        // Make room for function addresses
        out.seekp(NR_SIZE * functions.size(), std::ios::cur);
        std::vector<uint32_t> functionAddresses;
        for (size_t index = 0; index < functions.size(); ++index) {
            functionAddresses.push_back(out.tellp());
            FunctionData& function = functions[index];
            writeBuff.push_back(function.line);
            writeBuff.push_back(function.summedSelfCost);
            writeBuff.push_back(function.summedInclusiveCost);
            writeBuff.push_back(function.invocationCount);
            writeBuff.push_back(function.calledFromInformation.size());
            writeBuff.push_back(function.subCallInformation.size());
            writeBuffer(out, writeBuff);
            // Write called from information
            for (std::vector<CallData>::const_iterator cfiItr = function.calledFromInformation.begin();
                 cfiItr != function.calledFromInformation.end(); ++cfiItr) {
                const CallData& call = *cfiItr;
                writeBuff.push_back(call.functionNr);
                writeBuff.push_back(call.line);
                writeBuff.push_back(call.callCount);
                writeBuff.push_back(call.summedCallCost);
                writeBuffer(out, writeBuff);
            }
            // Write sub call information
            for (std::vector<CallData>::const_iterator sciItr = function.subCallInformation.begin();
                 sciItr != function.subCallInformation.end(); ++sciItr) {
                const CallData& call = *sciItr;
                writeBuff.push_back(call.functionNr);
                writeBuff.push_back(call.line);
                writeBuff.push_back(call.callCount);
                writeBuff.push_back(call.summedCallCost);
                writeBuffer(out, writeBuff);
            }

            out << function.filename << '\n' << reFunctionNames[index] << '\n';
        }
        size_t headersPos = out.tellp();
        // Write headers
        for (std::vector<std::string>::const_iterator hItr = headers.begin();
             hItr != headers.end(); ++hItr) {
            out << *hItr << '\n';
        }

        // Write addresses
        out.seekp(NR_SIZE, std::ios::beg);
        writeBuff.push_back(headersPos);
        writeBuffer(out, writeBuff);
        // Skip function count
        out.seekp(NR_SIZE, std::ios::cur);
        // Write function addresses
        writeBuffer(out, functionAddresses);

        out.close();
    }

private:

    void getCompressedName(std::string& name, bool isFile)
    {
        if (name[0] != '(' || !std::isdigit(name[1])) {
            return;
        }
        int functionIndex = std::atoi(name.c_str() + 1);
        size_t idx = name.find(')');
        if (idx + 2 < name.length()) {
            name.erase(0, idx + 2);
            compressedNames[isFile][functionIndex] = name;
        } else {
            std::map<int, std::string>::iterator nmIt = compressedNames[isFile].find(functionIndex);
            if (nmIt != compressedNames[isFile].end()) {
                name = nmIt->second; // should always exist for valid files
            }
        }
    }

    void writeBuffer(std::ostream& out, std::vector<uint32_t>& buffer)
    {
        for (std::vector<uint32_t>::iterator bItr = buffer.begin(); bItr != buffer.end(); ++bItr) {
            *bItr = toLittleEndian32(*bItr);
        }
        out.write(reinterpret_cast<const char*>(&buffer.front()), sizeof(uint32_t) * buffer.size());
        buffer.clear();
    }

    uint32_t toLittleEndian32(uint32_t value)
    {
        value = htonl(value);
        uint32_t result = 0;
        result |= (value & 0x000000FF) << 24;
        result |= (value & 0x0000FF00) <<  8;
        result |= (value & 0x00FF0000) >>  8;
        result |= (value & 0xFF000000) >> 24;
        return result;
    }

    std::map<int, std::string> compressedNames [2];
};

int main(int argc, char* argv[])
{
    if (argc < 3) {
        return 1;
    }
    std::vector<std::string> proxyFunctions;
    for (int argIdx = 3; argIdx < argc; ++ argIdx) {
        proxyFunctions.push_back(argv[argIdx]);
    }
    std::sort(proxyFunctions.begin(), proxyFunctions.end());
    Webgrind_Preprocessor processor;
    processor.parse(argv[1], argv[2], proxyFunctions);
    return 0;
}