blob: 6ce53aee081ab4e487424a0b7f8f9ae23de852c2 [file] [log] [blame]
Ben Claytoneea9d352019-08-29 01:05:14 +01001// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef sw_Memset_hpp
16#define sw_Memset_hpp
17
18#include <cstring>
19#include <type_traits>
20
Nicolas Capens157ba262019-12-10 17:49:14 -050021namespace sw {
22
23// Helper class for clearing the memory of objects at construction.
24// Useful as the first base class of cache keys which may contain padding
25// bytes or bits otherwise left uninitialized.
26template<class T>
27struct Memset
Ben Claytoneea9d352019-08-29 01:05:14 +010028{
Nicolas Capens157ba262019-12-10 17:49:14 -050029 Memset(T *object, int val)
Ben Claytoneea9d352019-08-29 01:05:14 +010030 {
Nicolas Capens157ba262019-12-10 17:49:14 -050031 static_assert(std::is_base_of<Memset<T>, T>::value, "Memset<T> must only clear the memory of a type of which it is a base class");
Ben Claytoneea9d352019-08-29 01:05:14 +010032
Ben Claytonfccfc562019-12-17 20:37:31 +000033// GCC 8+ warns that
34// "‘void* memset(void*, int, size_t)’ clearing an object of non-trivial type ‘T’;
35// use assignment or value-initialization instead [-Werror=class-memaccess]"
36// This is benign iff it happens before any of the base or member constructrs are called.
37#if defined(__GNUC__) && (__GNUC__ >= 8)
38# pragma GCC diagnostic push
39# pragma GCC diagnostic ignored "-Wclass-memaccess"
40#endif
Ben Claytoneea9d352019-08-29 01:05:14 +010041
Nicolas Capens157ba262019-12-10 17:49:14 -050042 memset(object, 0, sizeof(T));
Ben Claytoneea9d352019-08-29 01:05:14 +010043
Ben Claytonfccfc562019-12-17 20:37:31 +000044#if defined(__GNUC__) && (__GNUC__ >= 8)
45# pragma GCC diagnostic pop
46#endif
Nicolas Capens157ba262019-12-10 17:49:14 -050047 }
48};
Ben Claytoneea9d352019-08-29 01:05:14 +010049
Nicolas Capens157ba262019-12-10 17:49:14 -050050} // namespace sw
Ben Claytoneea9d352019-08-29 01:05:14 +010051
Ben Claytonfccfc562019-12-17 20:37:31 +000052#endif // sw_Memset_hpp