xref: /aosp_15_r20/external/mesa3d/src/compiler/glsl/shader_cache.cpp (revision 6104692788411f58d303aa86923a9ff6ecaded22)
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 "util/os_misc.h"
48 
49 #include "compiler/shader_info.h"
50 #include "glsl_symbol_table.h"
51 #include "glsl_parser_extras.h"
52 #include "ir.h"
53 #include "ir_optimization.h"
54 #include "ir_rvalue_visitor.h"
55 #include "ir_uniform.h"
56 #include "linker.h"
57 #include "nir.h"
58 #include "program.h"
59 #include "serialize.h"
60 #include "shader_cache.h"
61 #include "util/mesa-sha1.h"
62 #include "string_to_uint_map.h"
63 #include "main/mtypes.h"
64 
65 extern "C" {
66 #include "main/enums.h"
67 #include "main/shaderobj.h"
68 #include "program/program.h"
69 }
70 
71 static void
compile_shaders(struct gl_context * ctx,struct gl_shader_program * prog)72 compile_shaders(struct gl_context *ctx, struct gl_shader_program *prog) {
73    for (unsigned i = 0; i < prog->NumShaders; i++) {
74       _mesa_glsl_compile_shader(ctx, prog->Shaders[i], false, false, true);
75    }
76 }
77 
78 static void
create_binding_str(const char * key,unsigned value,void * closure)79 create_binding_str(const char *key, unsigned value, void *closure)
80 {
81    char **bindings_str = (char **) closure;
82    ralloc_asprintf_append(bindings_str, "%s:%u,", key, value);
83 }
84 
85 void
shader_cache_write_program_metadata(struct gl_context * ctx,struct gl_shader_program * prog)86 shader_cache_write_program_metadata(struct gl_context *ctx,
87                                     struct gl_shader_program *prog)
88 {
89    struct disk_cache *cache = ctx->Cache;
90    if (!cache)
91       return;
92 
93    /* Exit early when we are dealing with a ff shader with no source file to
94     * generate a source from, or with a SPIR-V shader.
95     *
96     * TODO: In future we should use another method to generate a key for ff
97     * programs, and SPIR-V shaders.
98     */
99    static const char zero[sizeof(prog->data->sha1)] = {0};
100    if (memcmp(prog->data->sha1, zero, sizeof(prog->data->sha1)) == 0)
101       return;
102 
103    struct blob metadata;
104    blob_init(&metadata);
105 
106    if (ctx->Driver.ShaderCacheSerializeDriverBlob) {
107       for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
108          struct gl_linked_shader *sh = prog->_LinkedShaders[i];
109          if (sh)
110             ctx->Driver.ShaderCacheSerializeDriverBlob(ctx, sh->Program);
111       }
112    }
113 
114    serialize_glsl_program(&metadata, ctx, prog);
115 
116    struct cache_item_metadata cache_item_metadata;
117    cache_item_metadata.type = CACHE_ITEM_TYPE_GLSL;
118    cache_item_metadata.keys =
119       (cache_key *) malloc(prog->NumShaders * sizeof(cache_key));
120    cache_item_metadata.num_keys = prog->NumShaders;
121 
122    if (!cache_item_metadata.keys)
123       goto fail;
124 
125    for (unsigned i = 0; i < prog->NumShaders; i++) {
126       memcpy(cache_item_metadata.keys[i], prog->Shaders[i]->disk_cache_sha1,
127              sizeof(cache_key));
128    }
129 
130    disk_cache_put(cache, prog->data->sha1, metadata.data, metadata.size,
131                   &cache_item_metadata);
132 
133    char sha1_buf[41];
134    if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
135       _mesa_sha1_format(sha1_buf, prog->data->sha1);
136       fprintf(stderr, "putting program metadata in cache: %s\n", sha1_buf);
137    }
138 
139 fail:
140    free(cache_item_metadata.keys);
141    blob_finish(&metadata);
142 }
143 
144 bool
shader_cache_read_program_metadata(struct gl_context * ctx,struct gl_shader_program * prog)145 shader_cache_read_program_metadata(struct gl_context *ctx,
146                                    struct gl_shader_program *prog)
147 {
148    /* Fixed function programs generated by Mesa, or SPIR-V shaders, are not
149     * cached. So don't try to read metadata for them from the cache.
150     */
151    if (prog->Name == 0 || prog->data->spirv)
152       return false;
153 
154    struct disk_cache *cache = ctx->Cache;
155    if (!cache)
156       return false;
157 
158    /* Include bindings when creating sha1. These bindings change the resulting
159     * binary so they are just as important as the shader source.
160     */
161    char *buf = ralloc_strdup(NULL, "vb: ");
162    prog->AttributeBindings->iterate(create_binding_str, &buf);
163    ralloc_strcat(&buf, "fb: ");
164    prog->FragDataBindings->iterate(create_binding_str, &buf);
165    ralloc_strcat(&buf, "fbi: ");
166    prog->FragDataIndexBindings->iterate(create_binding_str, &buf);
167    ralloc_asprintf_append(&buf, "tf: %d ", prog->TransformFeedback.BufferMode);
168    for (unsigned int i = 0; i < prog->TransformFeedback.NumVarying; i++) {
169       ralloc_asprintf_append(&buf, "%s ",
170                              prog->TransformFeedback.VaryingNames[i]);
171    }
172 
173    /* SSO has an effect on the linked program so include this when generating
174     * the sha also.
175     */
176    ralloc_asprintf_append(&buf, "sso: %s\n",
177                           prog->SeparateShader ? "T" : "F");
178 
179    /* A shader might end up producing different output depending on the glsl
180     * version supported by the compiler. For example a different path might be
181     * taken by the preprocessor, so add the version to the hash input.
182     */
183    ralloc_asprintf_append(&buf, "api: %d glsl: %d fglsl: %d\n",
184                           ctx->API, ctx->Const.GLSLVersion,
185                           ctx->Const.ForceGLSLVersion);
186 
187    /* We run the preprocessor on shaders after hashing them, so we need to
188     * add any extension override vars to the hash. If we don't do this the
189     * preprocessor could result in different output and we could load the
190     * wrong shader.
191     */
192    const char *ext_override = os_get_option("MESA_EXTENSION_OVERRIDE");
193    if (ext_override) {
194       ralloc_asprintf_append(&buf, "ext:%s", ext_override);
195    }
196 
197    /* DRI config options may also change the output from the compiler so
198     * include them as an input to sha1 creation.
199     */
200    char sha1buf[41];
201    _mesa_sha1_format(sha1buf, ctx->Const.dri_config_options_sha1);
202    ralloc_strcat(&buf, sha1buf);
203 
204    for (unsigned i = 0; i < prog->NumShaders; i++) {
205       struct gl_shader *sh = prog->Shaders[i];
206       _mesa_sha1_format(sha1buf, sh->disk_cache_sha1);
207       ralloc_asprintf_append(&buf, "%s: %s\n",
208                              _mesa_shader_stage_to_abbrev(sh->Stage), sha1buf);
209    }
210    disk_cache_compute_key(cache, buf, strlen(buf), prog->data->sha1);
211    ralloc_free(buf);
212 
213    size_t size;
214    uint8_t *buffer = (uint8_t *) disk_cache_get(cache, prog->data->sha1,
215                                                 &size);
216    if (buffer == NULL) {
217       /* Cached program not found. We may have seen the individual shaders
218        * before and skipped compiling but they may not have been used together
219        * in this combination before. Fall back to linking shaders but first
220        * re-compile the shaders.
221        *
222        * We could probably only compile the shaders which were skipped here
223        * but we need to be careful because the source may also have been
224        * changed since the last compile so for now we just recompile
225        * everything.
226        */
227       compile_shaders(ctx, prog);
228       return false;
229    }
230 
231    if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
232       _mesa_sha1_format(sha1buf, prog->data->sha1);
233       fprintf(stderr, "loading shader program meta data from cache: %s\n",
234               sha1buf);
235    }
236 
237    struct blob_reader metadata;
238    blob_reader_init(&metadata, buffer, size);
239 
240    bool deserialized = deserialize_glsl_program(&metadata, ctx, prog);
241 
242    if (!deserialized || metadata.current != metadata.end || metadata.overrun) {
243       /* Something has gone wrong discard the item from the cache and rebuild
244        * from source.
245        */
246       assert(!"Invalid GLSL shader disk cache item!");
247 
248       if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
249          fprintf(stderr, "Error reading program from cache (invalid GLSL "
250                  "cache item)\n");
251       }
252 
253       disk_cache_remove(cache, prog->data->sha1);
254       compile_shaders(ctx, prog);
255       free(buffer);
256       return false;
257    }
258 
259    /* This is used to flag a shader retrieved from cache */
260    prog->data->LinkStatus = LINKING_SKIPPED;
261 
262    free (buffer);
263 
264    return true;
265 }
266