1 /*
2  * Copyright © 2014 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 /**
25  * \file shader_cache.cpp
26  *
27  * GLSL shader cache implementation
28  *
29  * This uses disk_cache.c to write out a serialization of various
30  * state that's required in order to successfully load and use a
31  * binary written out by a drivers backend, this state is referred to as
32  * "metadata" throughout the implementation.
33  *
34  * The hash key for glsl metadata is a hash of the hashes of each GLSL
35  * source string as well as some API settings that change the final program
36  * such as SSO, attribute bindings, frag data bindings, etc.
37  *
38  * In order to avoid caching any actual IR we use the put_key/get_key support
39  * in the disk_cache to put the SHA-1 hash for each successfully compiled
40  * shader into the cache, and optimisticly return early from glCompileShader
41  * (if the identical shader had been successfully compiled in the past),
42  * in the hope that the final linked shader will be found in the cache.
43  * If anything goes wrong (shader variant not found, backend cache item is
44  * corrupt, etc) we will use a fallback path to compile and link the IR.
45  */
46 
47 #include "compiler/shader_info.h"
48 #include "glsl_symbol_table.h"
49 #include "glsl_parser_extras.h"
50 #include "ir.h"
51 #include "ir_optimization.h"
52 #include "ir_rvalue_visitor.h"
53 #include "ir_uniform.h"
54 #include "linker.h"
55 #include "link_varyings.h"
56 #include "program.h"
57 #include "serialize.h"
58 #include "shader_cache.h"
59 #include "util/mesa-sha1.h"
60 #include "string_to_uint_map.h"
61 #include "main/mtypes.h"
62 
63 extern "C" {
64 #include "main/enums.h"
65 #include "main/shaderobj.h"
66 #include "program/program.h"
67 }
68 
69 static void
compile_shaders(struct gl_context * ctx,struct gl_shader_program * prog)70 compile_shaders(struct gl_context *ctx, struct gl_shader_program *prog) {
71    for (unsigned i = 0; i < prog->NumShaders; i++) {
72       _mesa_glsl_compile_shader(ctx, prog->Shaders[i], false, false, true);
73    }
74 }
75 
76 static void
create_binding_str(const char * key,unsigned value,void * closure)77 create_binding_str(const char *key, unsigned value, void *closure)
78 {
79    char **bindings_str = (char **) closure;
80    ralloc_asprintf_append(bindings_str, "%s:%u,", key, value);
81 }
82 
83 void
shader_cache_write_program_metadata(struct gl_context * ctx,struct gl_shader_program * prog)84 shader_cache_write_program_metadata(struct gl_context *ctx,
85                                     struct gl_shader_program *prog)
86 {
87    struct disk_cache *cache = ctx->Cache;
88    if (!cache)
89       return;
90 
91    /* Exit early when we are dealing with a ff shader with no source file to
92     * generate a source from, or with a SPIR-V shader.
93     *
94     * TODO: In future we should use another method to generate a key for ff
95     * programs, and SPIR-V shaders.
96     */
97    static const char zero[sizeof(prog->data->sha1)] = {0};
98    if (memcmp(prog->data->sha1, zero, sizeof(prog->data->sha1)) == 0)
99       return;
100 
101    struct blob metadata;
102    blob_init(&metadata);
103 
104    if (ctx->Driver.ShaderCacheSerializeDriverBlob) {
105       for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
106          struct gl_linked_shader *sh = prog->_LinkedShaders[i];
107          if (sh)
108             ctx->Driver.ShaderCacheSerializeDriverBlob(ctx, sh->Program);
109       }
110    }
111 
112    serialize_glsl_program(&metadata, ctx, prog);
113 
114    struct cache_item_metadata cache_item_metadata;
115    cache_item_metadata.type = CACHE_ITEM_TYPE_GLSL;
116    cache_item_metadata.keys =
117       (cache_key *) malloc(prog->NumShaders * sizeof(cache_key));
118    cache_item_metadata.num_keys = prog->NumShaders;
119 
120    if (!cache_item_metadata.keys)
121       goto fail;
122 
123    for (unsigned i = 0; i < prog->NumShaders; i++) {
124       memcpy(cache_item_metadata.keys[i], prog->Shaders[i]->sha1,
125              sizeof(cache_key));
126    }
127 
128    disk_cache_put(cache, prog->data->sha1, metadata.data, metadata.size,
129                   &cache_item_metadata);
130 
131    char sha1_buf[41];
132    if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
133       _mesa_sha1_format(sha1_buf, prog->data->sha1);
134       fprintf(stderr, "putting program metadata in cache: %s\n", sha1_buf);
135    }
136 
137 fail:
138    free(cache_item_metadata.keys);
139    blob_finish(&metadata);
140 }
141 
142 bool
shader_cache_read_program_metadata(struct gl_context * ctx,struct gl_shader_program * prog)143 shader_cache_read_program_metadata(struct gl_context *ctx,
144                                    struct gl_shader_program *prog)
145 {
146    /* Fixed function programs generated by Mesa, or SPIR-V shaders, are not
147     * cached. So don't try to read metadata for them from the cache.
148     */
149    if (prog->Name == 0 || prog->data->spirv)
150       return false;
151 
152    struct disk_cache *cache = ctx->Cache;
153    if (!cache)
154       return false;
155 
156    /* Include bindings when creating sha1. These bindings change the resulting
157     * binary so they are just as important as the shader source.
158     */
159    char *buf = ralloc_strdup(NULL, "vb: ");
160    prog->AttributeBindings->iterate(create_binding_str, &buf);
161    ralloc_strcat(&buf, "fb: ");
162    prog->FragDataBindings->iterate(create_binding_str, &buf);
163    ralloc_strcat(&buf, "fbi: ");
164    prog->FragDataIndexBindings->iterate(create_binding_str, &buf);
165    ralloc_asprintf_append(&buf, "tf: %d ", prog->TransformFeedback.BufferMode);
166    for (unsigned int i = 0; i < prog->TransformFeedback.NumVarying; i++) {
167       ralloc_asprintf_append(&buf, "%s ",
168                              prog->TransformFeedback.VaryingNames[i]);
169    }
170 
171    /* SSO has an effect on the linked program so include this when generating
172     * the sha also.
173     */
174    ralloc_asprintf_append(&buf, "sso: %s\n",
175                           prog->SeparateShader ? "T" : "F");
176 
177    /* A shader might end up producing different output depending on the glsl
178     * version supported by the compiler. For example a different path might be
179     * taken by the preprocessor, so add the version to the hash input.
180     */
181    ralloc_asprintf_append(&buf, "api: %d glsl: %d fglsl: %d\n",
182                           ctx->API, ctx->Const.GLSLVersion,
183                           ctx->Const.ForceGLSLVersion);
184 
185    /* We run the preprocessor on shaders after hashing them, so we need to
186     * add any extension override vars to the hash. If we don't do this the
187     * preprocessor could result in different output and we could load the
188     * wrong shader.
189     */
190    char *ext_override = getenv("MESA_EXTENSION_OVERRIDE");
191    if (ext_override) {
192       ralloc_asprintf_append(&buf, "ext:%s", ext_override);
193    }
194 
195    /* DRI config options may also change the output from the compiler so
196     * include them as an input to sha1 creation.
197     */
198    char sha1buf[41];
199    _mesa_sha1_format(sha1buf, ctx->Const.dri_config_options_sha1);
200    ralloc_strcat(&buf, sha1buf);
201 
202    for (unsigned i = 0; i < prog->NumShaders; i++) {
203       struct gl_shader *sh = prog->Shaders[i];
204       _mesa_sha1_format(sha1buf, sh->sha1);
205       ralloc_asprintf_append(&buf, "%s: %s\n",
206                              _mesa_shader_stage_to_abbrev(sh->Stage), sha1buf);
207    }
208    disk_cache_compute_key(cache, buf, strlen(buf), prog->data->sha1);
209    ralloc_free(buf);
210 
211    size_t size;
212    uint8_t *buffer = (uint8_t *) disk_cache_get(cache, prog->data->sha1,
213                                                 &size);
214    if (buffer == NULL) {
215       /* Cached program not found. We may have seen the individual shaders
216        * before and skipped compiling but they may not have been used together
217        * in this combination before. Fall back to linking shaders but first
218        * re-compile the shaders.
219        *
220        * We could probably only compile the shaders which were skipped here
221        * but we need to be careful because the source may also have been
222        * changed since the last compile so for now we just recompile
223        * everything.
224        */
225       compile_shaders(ctx, prog);
226       return false;
227    }
228 
229    if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
230       _mesa_sha1_format(sha1buf, prog->data->sha1);
231       fprintf(stderr, "loading shader program meta data from cache: %s\n",
232               sha1buf);
233    }
234 
235    struct blob_reader metadata;
236    blob_reader_init(&metadata, buffer, size);
237 
238    bool deserialized = deserialize_glsl_program(&metadata, ctx, prog);
239 
240    if (!deserialized || metadata.current != metadata.end || metadata.overrun) {
241       /* Something has gone wrong discard the item from the cache and rebuild
242        * from source.
243        */
244       assert(!"Invalid GLSL shader disk cache item!");
245 
246       if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
247          fprintf(stderr, "Error reading program from cache (invalid GLSL "
248                  "cache item)\n");
249       }
250 
251       disk_cache_remove(cache, prog->data->sha1);
252       compile_shaders(ctx, prog);
253       free(buffer);
254       return false;
255    }
256 
257    /* This is used to flag a shader retrieved from cache */
258    prog->data->LinkStatus = LINKING_SKIPPED;
259 
260    free (buffer);
261 
262    return true;
263 }
264