]> git.cworth.org Git - apitrace/blob - cli/cli_trim.cpp
trim: Conservatively make shader programs depend on textures
[apitrace] / cli / cli_trim.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010 VMware, Inc.
4  * Copyright 2011 Intel corporation
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27 #include <sstream>
28 #include <string.h>
29 #include <limits.h> // for CHAR_MAX
30 #include <getopt.h>
31
32 #include <GL/gl.h>
33 #include <GL/glext.h>
34
35 #include <set>
36
37 #include "cli.hpp"
38
39 #include "os_string.hpp"
40
41 #include "trace_callset.hpp"
42 #include "trace_parser.hpp"
43 #include "trace_writer.hpp"
44
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
46 #define STRNCMP_LITERAL(var, literal) strncmp((var), (literal), sizeof (literal) -1)
47
48 static const char *synopsis = "Create a new trace by trimming an existing trace.";
49
50 static void
51 usage(void)
52 {
53     std::cout
54         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
55         << synopsis << "\n"
56         "\n"
57         "    -h, --help               Show detailed help for trim options and exit\n"
58         "        --calls=CALLSET      Include specified calls in the trimmed output.\n"
59         "        --frames=FRAMESET    Include specified frames in the trimmed output.\n"
60         "        --deps               Include additional calls to satisfy dependencies\n"
61         "        --no-deps            Do not include calls from dependency analysis\n"
62         "        --prune              Omit uninteresting calls from the trace output\n"
63         "        --no-prune           Do not prune uninteresting calls from the trace.\n"
64         "    -x, --exact              Trim exactly to calls specified in --calls/--frames\n"
65         "                             Equivalent to both --no-deps and --no-prune\n"
66         "        --print-callset      Print the final set of calls included in output\n"
67         "        --thread=THREAD_ID   Only retain calls from specified thread\n"
68         "    -o, --output=TRACE_FILE  Output trace file\n"
69     ;
70 }
71
72 static void
73 help()
74 {
75     std::cout
76         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
77         << synopsis << "\n"
78         "\n"
79         "    -h, --help               Show this help message and exit\n"
80         "\n"
81         "        --calls=CALLSET      Include specified calls in the trimmed output.\n"
82         "        --frames=FRAMESET    Include specified frames in the trimmed output.\n"
83         "                             Note that due to dependency analysis and pruning\n"
84         "                             of uninteresting calls the resulting trace may\n"
85         "                             include more and less calls than specified.\n"
86         "                             See --no-deps, --no-prune, and --exact to change\n"
87         "                             this behavior.\n"
88         "\n"
89         "        --deps               Perform dependency analysis and include dependent\n"
90         "                             calls as needed, (even if those calls were not\n"
91         "                             explicitly requested with --calls or --frames).\n"
92         "                             This is the default behavior. See --no-deps and\n"
93         "                             --exact to change the behavior.\n"
94         "\n"
95         "        --no-deps            Do not perform dependency analysis. In this mode\n"
96         "                             the trimmed trace will never include calls from\n"
97         "                             outside what is specified in --calls or --frames.\n"
98         "\n"
99         "        --prune              Omit calls with no side effects, even if the call\n"
100         "                             is within the range specified by --calls/--frames.\n"
101         "                             This is the default behavior. See --no-prune.\n"
102         "\n"
103         "        --no-prune           Do not prune uninteresting calls from the trace.\n"
104         "                             In this mode the trimmed trace will never omit\n"
105         "                             any calls within the user-specified range.\n"
106         "\n"
107         "    -x, --exact              Trim the trace to exactly the calls specified in\n"
108         "                             --calls and --frames. This option is equivalent\n"
109         "                             to passing both --no-deps and --no-prune.\n"
110         "\n"
111         "        --print-callset      Print to stdout the final set of calls included\n"
112         "                             in the trim output. This can be useful for\n"
113         "                             debugging trim operations by using a modified\n"
114         "                             callset on the command-line along with --exact.\n"
115         "                             Use --calls=@<file> to read callset from a file.\n"
116         "\n"
117         "        --thread=THREAD_ID   Only retain calls from specified thread\n"
118         "\n"
119         "    -o, --output=TRACE_FILE  Output trace file\n"
120         "\n"
121     ;
122 }
123
124 enum {
125     CALLS_OPT = CHAR_MAX + 1,
126     FRAMES_OPT,
127     DEPS_OPT,
128     NO_DEPS_OPT,
129     PRUNE_OPT,
130     NO_PRUNE_OPT,
131     THREAD_OPT,
132     PRINT_CALLSET_OPT,
133 };
134
135 const static char *
136 shortOptions = "ho:x";
137
138 const static struct option
139 longOptions[] = {
140     {"help", no_argument, 0, 'h'},
141     {"calls", required_argument, 0, CALLS_OPT},
142     {"frames", required_argument, 0, FRAMES_OPT},
143     {"deps", no_argument, 0, DEPS_OPT},
144     {"no-deps", no_argument, 0, NO_DEPS_OPT},
145     {"prune", no_argument, 0, PRUNE_OPT},
146     {"no-prune", no_argument, 0, NO_PRUNE_OPT},
147     {"exact", no_argument, 0, 'x'},
148     {"thread", required_argument, 0, THREAD_OPT},
149     {"output", required_argument, 0, 'o'},
150     {"print-callset", no_argument, 0, PRINT_CALLSET_OPT},
151     {0, 0, 0, 0}
152 };
153
154 struct stringCompare {
155     bool operator() (const char *a, const char *b) const {
156         return strcmp(a, b) < 0;
157     }
158 };
159
160 class TraceAnalyzer {
161     /* Maps for tracking resource dependencies between calls. */
162     std::map<std::string, std::set<unsigned> > resources;
163     std::map<std::string, std::set<std::string> > dependencies;
164
165     /* Maps for tracking OpenGL state. */
166     std::map<GLenum, unsigned> texture_map;
167
168     /* The final set of calls required. This consists of calls added
169      * explicitly with the require() method as well as all calls
170      * implicitly required by those through resource dependencies. */
171     std::set<unsigned> required;
172
173     bool transformFeedbackActive;
174     bool framebufferObjectActive;
175     bool insideBeginEnd;
176     GLuint activeProgram;
177     GLenum activeTextureUnit;
178
179     /* Rendering often has no side effects, but it can in some cases,
180      * (such as when transform feedback is active, or when rendering
181      * targets a framebuffer object). */
182     bool renderingHasSideEffect() {
183         return transformFeedbackActive || framebufferObjectActive;
184     }
185
186     /* Provide: Record that the given call affects the given resource
187      * as a side effect. */
188     void provide(std::string resource, trace::CallNo call_no) {
189         resources[resource].insert(call_no);
190     }
191
192     /* Like provide, but with a simply-formatted string, (appending an
193      * integer to the given string). */
194     void providef(std::string resource, int resource_no, trace::CallNo call_no) {
195         std::stringstream ss;
196         ss << resource << resource_no;
197         provide(ss.str(), call_no);
198     }
199
200     /* Link: Establish a dependency between resource 'resource' and
201      * resource 'dependency'. This dependency is captured by name so
202      * that if the list of calls that provide 'dependency' grows
203      * before 'resource' is consumed, those calls will still be
204      * captured. */
205     void link(std::string resource, std::string dependency) {
206         dependencies[resource].insert(dependency);
207     }
208
209     /* Like link, but with a simply-formatted string, (appending an
210      * integer to the given string). */
211     void linkf(std::string resource, std::string dependency, int dep_no) {
212
213         std::stringstream ss;
214         ss << dependency << dep_no;
215         link(resource, ss.str());
216     }
217
218     /* Unlink: Remove dependency from 'resource' on 'dependency'. */
219     void unlink(std::string resource, std::string dependency) {
220         dependencies[resource].erase(dependency);
221         if (dependencies[resource].size() == 0) {
222             dependencies.erase(resource);
223         }
224     }
225
226     /* Like unlink, but with a simply-formated string, (appending an
227      * integer to the given string). */
228     void unlinkf(std::string resource, std::string dependency, int dep_no) {
229
230         std::stringstream ss;
231         ss << dependency << dep_no;
232         unlink(resource, ss.str());
233     }
234
235     /* Unlink all: Remove dependencies from 'resource' to all other
236      * resources. */
237     void unlinkAll(std::string resource) {
238         dependencies.erase(resource);
239     }
240
241     /* Resolve: Recursively compute all calls providing 'resource',
242      * (including linked dependencies of 'resource' on other
243      * resources). */
244     std::set<unsigned> resolve(std::string resource) {
245         std::set<std::string> *deps;
246         std::set<std::string>::iterator dep;
247
248         std::set<unsigned> *calls;
249         std::set<unsigned>::iterator call;
250
251         std::set<unsigned> result, deps_set;
252
253         /* Recursively chase dependencies. */
254         if (dependencies.count(resource)) {
255             deps = &dependencies[resource];
256             for (dep = deps->begin(); dep != deps->end(); dep++) {
257                 deps_set = resolve(*dep);
258                 for (call = deps_set.begin(); call != deps_set.end(); call++) {
259                     result.insert(*call);
260                 }
261             }
262         }
263
264         /* Also look for calls that directly provide 'resource' */
265         if (resources.count(resource)) {
266             calls = &resources[resource];
267             for (call = calls->begin(); call != calls->end(); call++) {
268                 result.insert(*call);
269             }
270         }
271
272         return result;
273     }
274
275     /* Consume: Resolve all calls that provide the given resource, and
276      * add them to the required list. Then clear the call list for
277      * 'resource' along with any dependencies. */
278     void consume(std::string resource) {
279
280         std::set<unsigned> calls;
281         std::set<unsigned>::iterator call;
282
283         calls = resolve(resource);
284
285         dependencies.erase(resource);
286         resources.erase(resource);
287
288         for (call = calls.begin(); call != calls.end(); call++) {
289             required.insert(*call);
290         }
291     }
292
293     void stateTrackPreCall(trace::Call *call) {
294
295         const char *name = call->name();
296
297         if (strcmp(name, "glBegin") == 0) {
298             insideBeginEnd = true;
299             return;
300         }
301
302         if (strcmp(name, "glBeginTransformFeedback") == 0) {
303             transformFeedbackActive = true;
304             return;
305         }
306
307         if (strcmp(name, "glActiveTexture") == 0) {
308             activeTextureUnit = static_cast<GLenum>(call->arg(0).toSInt());
309             return;
310         }
311
312         if (strcmp(name, "glBindTexture") == 0) {
313             GLenum target;
314             GLuint texture;
315
316             target = static_cast<GLenum>(call->arg(0).toSInt());
317             texture = call->arg(1).toUInt();
318
319             if (texture == 0) {
320                 texture_map.erase(target);
321             } else {
322                 texture_map[target] = texture;
323             }
324
325             return;
326         }
327
328         if (strcmp(name, "glUseProgram") == 0) {
329             activeProgram = call->arg(0).toUInt();
330         }
331
332         if (strcmp(name, "glBindFramebuffer") == 0) {
333             GLenum target;
334             GLuint framebuffer;
335
336             target = static_cast<GLenum>(call->arg(0).toSInt());
337             framebuffer = call->arg(1).toUInt();
338
339             if (target == GL_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER) {
340                 if (framebuffer == 0) {
341                     framebufferObjectActive = false;
342                 } else {
343                     framebufferObjectActive = true;
344                 }
345             }
346             return;
347         }
348     }
349
350     void stateTrackPostCall(trace::Call *call) {
351
352         const char *name = call->name();
353
354         if (strcmp(name, "glEnd") == 0) {
355             insideBeginEnd = false;
356             return;
357         }
358
359         if (strcmp(name, "glEndTransformFeedback") == 0) {
360             transformFeedbackActive = false;
361             return;
362         }
363
364         /* If this swapbuffers was included in the trace then it will
365          * have already consumed all framebuffer dependencies. If not,
366          * then clear them now so that they don't carry over into the
367          * next frame. */
368         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
369             call->flags & trace::CALL_FLAG_END_FRAME) {
370             dependencies.erase("framebuffer");
371             resources.erase("framebuffer");
372             return;
373         }
374     }
375
376     void recordSideEffects(trace::Call *call) {
377
378         const char *name = call->name();
379
380         /* If call is flagged as no side effects, then we are done here. */
381         if (call->flags & trace::CALL_FLAG_NO_SIDE_EFFECTS) {
382             return;
383         }
384
385         /* Similarly, swap-buffers calls don't have interesting side effects. */
386         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
387             call->flags & trace::CALL_FLAG_END_FRAME) {
388             return;
389         }
390
391         if (strcmp(name, "glGenTextures") == 0) {
392             const trace::Array *textures = dynamic_cast<const trace::Array *>(&call->arg(1));
393             size_t i;
394             GLuint texture;
395
396             if (textures) {
397                 for (i = 0; i < textures->size(); i++) {
398                     texture = textures->values[i]->toUInt();
399                     providef("texture-", texture, call->no);
400                 }
401             }
402             return;
403         }
404
405         if (strcmp(name, "glBindTexture") == 0) {
406             GLenum target;
407             GLuint texture;
408
409             std::stringstream ss_target, ss_texture;
410
411             target = static_cast<GLenum>(call->arg(0).toSInt());
412             texture = call->arg(1).toUInt();
413
414             ss_target << "texture-unit-" << activeTextureUnit << "-target-" << target;
415             ss_texture << "texture-" << texture;
416
417             resources.erase(ss_target.str());
418             provide(ss_target.str(), call->no);
419
420             unlinkAll(ss_target.str());
421             link(ss_target.str(), ss_texture.str());
422
423             return;
424         }
425
426         /* FIXME: Need to handle glMultTexImage and friends. */
427         if (STRNCMP_LITERAL(name, "glTexImage") == 0 ||
428             STRNCMP_LITERAL(name, "glTexSubImage") == 0 ||
429             STRNCMP_LITERAL(name, "glCopyTexImage") == 0 ||
430             STRNCMP_LITERAL(name, "glCopyTexSubImage") == 0 ||
431             STRNCMP_LITERAL(name, "glCompressedTexImage") == 0 ||
432             STRNCMP_LITERAL(name, "glCompressedTexSubImage") == 0 ||
433             strcmp(name, "glInvalidateTexImage") == 0 ||
434             strcmp(name, "glInvalidateTexSubImage") == 0) {
435
436             std::set<unsigned> *calls;
437             std::set<unsigned>::iterator c;
438             std::stringstream ss_target, ss_texture;
439
440             GLenum target = static_cast<GLenum>(call->arg(0).toSInt());
441
442             ss_target << "texture-unit-" << activeTextureUnit << "-target-" << target;
443             ss_texture << "texture-" << texture_map[target];
444
445             /* The texture resource depends on this call and any calls
446              * providing the given texture target. */
447             provide(ss_texture.str(), call->no);
448
449             if (resources.count(ss_target.str())) {
450                 calls = &resources[ss_target.str()];
451                 for (c = calls->begin(); c != calls->end(); c++) {
452                     provide(ss_texture.str(), *c);
453                 }
454             }
455
456             return;
457         }
458
459         if (strcmp(name, "glEnable") == 0) {
460             GLenum cap;
461
462             cap = static_cast<GLenum>(call->arg(0).toSInt());
463
464             if (cap == GL_TEXTURE_1D ||
465                 cap == GL_TEXTURE_2D ||
466                 cap == GL_TEXTURE_3D ||
467                 cap == GL_TEXTURE_CUBE_MAP)
468             {
469                 std::stringstream ss;
470
471                 ss << "texture-unit-" << activeTextureUnit << "-target-" << cap;
472
473                 link("render-state", ss.str());
474             }
475
476             provide("state", call->no);
477             return;
478         }
479
480         if (strcmp(name, "glDisable") == 0) {
481             GLenum cap;
482
483             cap = static_cast<GLenum>(call->arg(0).toSInt());
484
485             if (cap == GL_TEXTURE_1D ||
486                 cap == GL_TEXTURE_2D ||
487                 cap == GL_TEXTURE_3D ||
488                 cap == GL_TEXTURE_CUBE_MAP)
489             {
490                 std::stringstream ss;
491
492                 ss << "texture-unit-" << activeTextureUnit << "-target-" << cap;
493
494                 unlink("render-state", ss.str());
495             }
496
497             provide("state", call->no);
498             return;
499         }
500
501         if (strcmp(name, "glCreateShader") == 0 ||
502             strcmp(name, "glCreateShaderObjectARB") == 0) {
503
504             GLuint shader = call->ret->toUInt();
505             providef("shader-", shader, call->no);
506             return;
507         }
508
509         if (strcmp(name, "glShaderSource") == 0 ||
510             strcmp(name, "glShaderSourceARB") == 0 ||
511             strcmp(name, "glCompileShader") == 0 ||
512             strcmp(name, "glCompileShaderARB") == 0 ||
513             strcmp(name, "glGetShaderiv") == 0 ||
514             strcmp(name, "glGetShaderInfoLog") == 0) {
515
516             GLuint shader = call->arg(0).toUInt();
517             providef("shader-", shader, call->no);
518             return;
519         }
520
521         if (strcmp(name, "glCreateProgram") == 0 ||
522             strcmp(name, "glCreateProgramObjectARB") == 0) {
523
524             GLuint program = call->ret->toUInt();
525             providef("program-", program, call->no);
526             return;
527         }
528
529         if (strcmp(name, "glAttachShader") == 0 ||
530             strcmp(name, "glAttachObjectARB") == 0) {
531
532             GLuint program, shader;
533             std::stringstream ss_program, ss_shader;
534
535             program = call->arg(0).toUInt();
536             shader = call->arg(1).toUInt();
537
538             ss_program << "program-" << program;
539             ss_shader << "shader-" << shader;
540
541             link(ss_program.str(), ss_shader.str());
542             provide(ss_program.str(), call->no);
543
544             return;
545         }
546
547         if (strcmp(name, "glDetachShader") == 0 ||
548             strcmp(name, "glDetachObjectARB") == 0) {
549
550             GLuint program, shader;
551             std::stringstream ss_program, ss_shader;
552
553             program = call->arg(0).toUInt();
554             shader = call->arg(1).toUInt();
555
556             ss_program << "program-" << program;
557             ss_shader << "shader-" << shader;
558
559             unlink(ss_program.str(), ss_shader.str());
560
561             return;
562         }
563
564         if (strcmp(name, "glUseProgram") == 0 ||
565             strcmp(name, "glUseProgramObjectARB") == 0) {
566
567             GLuint program;
568
569             program = call->arg(0).toUInt();
570
571             unlinkAll("render-program-state");
572
573             if (program == 0) {
574                 unlink("render-state", "render-program-state");
575                 provide("state", call->no);
576             } else {
577                 std::stringstream ss;
578
579                 ss << "program-" << program;
580
581                 link("render-state", "render-program-state");
582                 link("render-program-state", ss.str());
583
584                 provide(ss.str(), call->no);
585             }
586
587             return;
588         }
589
590         if (strcmp(name, "glGetUniformLocation") == 0 ||
591             strcmp(name, "glGetUniformLocationARB") == 0 ||
592             strcmp(name, "glGetFragDataLocation") == 0 ||
593             strcmp(name, "glGetFragDataLocationEXT") == 0 ||
594             strcmp(name, "glGetSubroutineUniformLocation") == 0 ||
595             strcmp(name, "glGetProgramResourceLocation") == 0 ||
596             strcmp(name, "glGetProgramResourceLocationIndex") == 0 ||
597             strcmp(name, "glGetVaryingLocationNV") == 0) {
598
599             GLuint program = call->arg(0).toUInt();
600
601             providef("program-", program, call->no);
602
603             return;
604         }
605
606         /* For any call that accepts 'location' as its first argument,
607          * perform a lookup in our location->program map and add a
608          * dependence on the program we find there. */
609         if (call->sig->num_args > 0 &&
610             strcmp(call->sig->arg_names[0], "location") == 0) {
611
612             providef("program-", activeProgram, call->no);
613
614             /* We can't easily tell if this uniform is being used to
615              * associate a sampler in the shader with a texture
616              * unit. The conservative option is to assume that it is
617              * and create a link from the active program to any bound
618              * textures for the given unit number.
619              *
620              * FIXME: We should be doing the same thing for calls to
621              * glUniform1iv. */
622             if (strcmp(name, "glUniform1i") == 0 ||
623                 strcmp(name, "glUniform1iARB") == 0) {
624
625                 GLint max_unit = MAX(GL_MAX_TEXTURE_COORDS, GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
626
627                 GLint unit = call->arg(1).toSInt();
628                 std::stringstream ss_program;
629                 std::stringstream ss_texture;
630
631                 if (unit < max_unit) {
632
633                     ss_program << "program-" << activeProgram;
634
635                     ss_texture << "texture-unit-" << GL_TEXTURE0 + unit << "-target-";
636
637                     /* We don't know what target(s) might get bound to
638                      * this texture unit, so conservatively link to
639                      * all. Only bound textures will actually get inserted
640                      * into the output call stream. */
641                     linkf(ss_program.str(), ss_texture.str(), GL_TEXTURE_1D);
642                     linkf(ss_program.str(), ss_texture.str(), GL_TEXTURE_2D);
643                     linkf(ss_program.str(), ss_texture.str(), GL_TEXTURE_3D);
644                     linkf(ss_program.str(), ss_texture.str(), GL_TEXTURE_CUBE_MAP);
645                 }
646             }
647
648             return;
649         }
650
651         /* FIXME: We cut a huge swath by assuming that any unhandled
652          * call that has a first argument named "program" should not
653          * be included in the trimmed output unless the program of
654          * that number is also included.
655          *
656          * This heuristic is correct for many cases, but we should
657          * actually carefully verify if this includes some calls
658          * inappropriately, or if it misses some.
659          */
660         if (strcmp(name, "glLinkProgram") == 0 ||
661             strcmp(name, "glLinkProgramARB") == 0 ||
662             (call->sig->num_args > 0 &&
663              (strcmp(call->sig->arg_names[0], "program") == 0 ||
664               strcmp(call->sig->arg_names[0], "programObj") == 0))) {
665
666             GLuint program = call->arg(0).toUInt();
667             providef("program-", program, call->no);
668             return;
669         }
670
671         /* Handle all rendering operations, (even though only glEnd is
672          * flagged as a rendering operation we treat everything from
673          * glBegin through glEnd as a rendering operation). */
674         if (call->flags & trace::CALL_FLAG_RENDER ||
675             insideBeginEnd) {
676
677             std::set<unsigned> calls;
678             std::set<unsigned>::iterator c;
679
680             provide("framebuffer", call->no);
681
682             calls = resolve("render-state");
683
684             for (c = calls.begin(); c != calls.end(); c++) {
685                 provide("framebuffer", *c);
686             }
687
688             /* In some cases, rendering has side effects beyond the
689              * framebuffer update. */
690             if (renderingHasSideEffect()) {
691                 provide("state", call->no);
692                 for (c = calls.begin(); c != calls.end(); c++) {
693                     provide("state", *c);
694                 }
695             }
696
697             return;
698         }
699
700         /* By default, assume this call affects the state somehow. */
701         resources["state"].insert(call->no);
702     }
703
704     void requireDependencies(trace::Call *call) {
705
706         /* Swap-buffers calls depend on framebuffer state. */
707         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
708             call->flags & trace::CALL_FLAG_END_FRAME) {
709             consume("framebuffer");
710         }
711
712         /* By default, just assume this call depends on generic state. */
713         consume("state");
714     }
715
716
717 public:
718     TraceAnalyzer(): transformFeedbackActive(false),
719                      framebufferObjectActive(false),
720                      insideBeginEnd(false),
721                      activeTextureUnit(GL_TEXTURE0)
722     {}
723
724     ~TraceAnalyzer() {}
725
726     /* Analyze this call by tracking state and recording all the
727      * resources provided by this call as side effects.. */
728     void analyze(trace::Call *call) {
729
730         stateTrackPreCall(call);
731
732         recordSideEffects(call);
733
734         stateTrackPostCall(call);
735     }
736
737     /* Require this call and all of its dependencies to be included in
738      * the final trace. */
739     void require(trace::Call *call) {
740
741         /* First, find and insert all calls that this call depends on. */
742         requireDependencies(call);
743
744         /* Then insert this call itself. */
745         required.insert(call->no);
746     }
747
748     /* Return a set of all the required calls, (both those calls added
749      * explicitly with require() and those implicitly depended
750      * upon. */
751     std::set<unsigned> *get_required(void) {
752         return &required;
753     }
754 };
755
756 struct trim_options {
757     /* Calls to be included in trace. */
758     trace::CallSet calls;
759
760     /* Frames to be included in trace. */
761     trace::CallSet frames;
762
763     /* Whether dependency analysis should be performed. */
764     bool dependency_analysis;
765
766     /* Whether uninteresting calls should be pruned.. */
767     bool prune_uninteresting;
768
769     /* Output filename */
770     std::string output;
771
772     /* Emit only calls from this thread (-1 == all threads) */
773     int thread;
774
775     /* Print resulting callset */
776     int print_callset;
777 };
778
779 static int
780 trim_trace(const char *filename, struct trim_options *options)
781 {
782     trace::ParseBookmark beginning;
783     trace::Parser p;
784     TraceAnalyzer analyzer;
785     std::set<unsigned> *required;
786     unsigned frame;
787     int call_range_first, call_range_last;
788
789     if (!p.open(filename)) {
790         std::cerr << "error: failed to open " << filename << "\n";
791         return 1;
792     }
793
794     /* Mark the beginning so we can return here for pass 2. */
795     p.getBookmark(beginning);
796
797     /* In pass 1, analyze which calls are needed. */
798     frame = 0;
799     trace::Call *call;
800     while ((call = p.parse_call())) {
801
802         /* There's no use doing any work past the last call or frame
803          * requested by the user. */
804         if (call->no > options->calls.getLast() ||
805             frame > options->frames.getLast()) {
806             
807             delete call;
808             break;
809         }
810
811         /* If requested, ignore all calls not belonging to the specified thread. */
812         if (options->thread != -1 && call->thread_id != options->thread) {
813             goto NEXT;
814         }
815
816         /* Also, prune if uninteresting (unless the user asked for no pruning. */
817         if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {
818             goto NEXT;
819         }
820
821         /* If this call is included in the user-specified call set,
822          * then require it (and all dependencies) in the trimmed
823          * output. */
824         if (options->calls.contains(*call) ||
825             options->frames.contains(frame, call->flags)) {
826
827             analyzer.require(call);
828         }
829
830         /* Regardless of whether we include this call or not, we do
831          * some dependency tracking (unless disabled by the user). We
832          * do this even for calls we have included in the output so
833          * that any state updates get performed. */
834         if (options->dependency_analysis) {
835             analyzer.analyze(call);
836         }
837
838     NEXT:
839         if (call->flags & trace::CALL_FLAG_END_FRAME)
840             frame++;
841
842         delete call;
843     }
844
845     /* Prepare output file and writer for output. */
846     if (options->output.empty()) {
847         os::String base(filename);
848         base.trimExtension();
849
850         options->output = std::string(base.str()) + std::string("-trim.trace");
851     }
852
853     trace::Writer writer;
854     if (!writer.open(options->output.c_str())) {
855         std::cerr << "error: failed to create " << filename << "\n";
856         return 1;
857     }
858
859     /* Reset bookmark for pass 2. */
860     p.setBookmark(beginning);
861
862     /* In pass 2, emit the calls that are required. */
863     required = analyzer.get_required();
864
865     frame = 0;
866     call_range_first = -1;
867     call_range_last = -1;
868     while ((call = p.parse_call())) {
869
870         /* There's no use doing any work past the last call or frame
871          * requested by the user. */
872         if (call->no > options->calls.getLast() ||
873             frame > options->frames.getLast()) {
874
875             break;
876         }
877
878         if (required->find(call->no) != required->end()) {
879             writer.writeCall(call);
880
881             if (options->print_callset) {
882                 if (call_range_first < 0) {
883                     call_range_first = call->no;
884                     printf ("%d", call_range_first);
885                 } else if (call->no != call_range_last + 1) {
886                     if (call_range_last != call_range_first)
887                         printf ("-%d", call_range_last);
888                     call_range_first = call->no;
889                     printf (",%d", call_range_first);
890                 }
891                 call_range_last = call->no;
892             }
893         }
894
895         if (call->flags & trace::CALL_FLAG_END_FRAME) {
896             frame++;
897         }
898
899         delete call;
900     }
901
902     if (options->print_callset) {
903         if (call_range_last != call_range_first)
904             printf ("-%d\n", call_range_last);
905     }
906
907     std::cout << "Trimmed trace is available as " << options->output << "\n";
908
909     return 0;
910 }
911
912 static int
913 command(int argc, char *argv[])
914 {
915     struct trim_options options;
916
917     options.calls = trace::CallSet(trace::FREQUENCY_NONE);
918     options.frames = trace::CallSet(trace::FREQUENCY_NONE);
919     options.dependency_analysis = true;
920     options.prune_uninteresting = true;
921     options.output = "";
922     options.thread = -1;
923     options.print_callset = 0;
924
925     int opt;
926     while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
927         switch (opt) {
928         case 'h':
929             help();
930             return 0;
931         case CALLS_OPT:
932             options.calls = trace::CallSet(optarg);
933             break;
934         case FRAMES_OPT:
935             options.frames = trace::CallSet(optarg);
936             break;
937         case DEPS_OPT:
938             options.dependency_analysis = true;
939             break;
940         case NO_DEPS_OPT:
941             options.dependency_analysis = false;
942             break;
943         case PRUNE_OPT:
944             options.prune_uninteresting = true;
945             break;
946         case NO_PRUNE_OPT:
947             options.prune_uninteresting = false;
948             break;
949         case 'x':
950             options.dependency_analysis = false;
951             options.prune_uninteresting = false;
952             break;
953         case THREAD_OPT:
954             options.thread = atoi(optarg);
955             break;
956         case 'o':
957             options.output = optarg;
958             break;
959         case PRINT_CALLSET_OPT:
960             options.print_callset = 1;
961             break;
962         default:
963             std::cerr << "error: unexpected option `" << opt << "`\n";
964             usage();
965             return 1;
966         }
967     }
968
969     /* If neither of --calls nor --frames was set, default to the
970      * entire set of calls. */
971     if (options.calls.empty() && options.frames.empty()) {
972         options.calls = trace::CallSet(trace::FREQUENCY_ALL);
973     }
974
975     if (optind >= argc) {
976         std::cerr << "error: apitrace trim requires a trace file as an argument.\n";
977         usage();
978         return 1;
979     }
980
981     if (argc > optind + 1) {
982         std::cerr << "error: extraneous arguments:";
983         for (int i = optind + 1; i < argc; i++) {
984             std::cerr << " " << argv[i];
985         }
986         std::cerr << "\n";
987         usage();
988         return 1;
989     }
990
991     return trim_trace(argv[optind], &options);
992 }
993
994 const Command trim_command = {
995     "trim",
996     synopsis,
997     help,
998     command
999 };