]> git.sesse.net Git - stockfish/blob - src/tt.cpp
Double prefetch on Windows
[stockfish] / src / tt.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2009 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cmath>
27 #include <cstring>
28
29 #include "movegen.h"
30 #include "tt.h"
31
32 #if defined(_MSC_VER)
33 #include <xmmintrin.h>
34 #endif
35
36 // This is the number of TTEntry slots for each position
37 static const int ClusterSize = 4;
38
39 // The main transposition table
40 TranspositionTable TT;
41
42 ////
43 //// Functions
44 ////
45
46 TranspositionTable::TranspositionTable() {
47
48   size = writes = 0;
49   entries = 0;
50   generation = 0;
51 }
52
53 TranspositionTable::~TranspositionTable() {
54
55   delete [] entries;
56 }
57
58
59 /// TranspositionTable::set_size sets the size of the transposition table,
60 /// measured in megabytes.
61
62 void TranspositionTable::set_size(unsigned mbSize) {
63
64   assert(mbSize >= 4 && mbSize <= 4096);
65
66   unsigned newSize = 1024;
67
68   // We store a cluster of ClusterSize number of TTEntry for each position
69   // and newSize is the maximum number of storable positions.
70   while ((2 * newSize) * ClusterSize * (sizeof(TTEntry)) <= (mbSize << 20))
71       newSize *= 2;
72
73   if (newSize != size)
74   {
75       size = newSize;
76       delete [] entries;
77       entries = new TTEntry[size * ClusterSize];
78       if (!entries)
79       {
80           std::cerr << "Failed to allocate " << mbSize
81                     << " MB for transposition table." << std::endl;
82           Application::exit_with_failure();
83       }
84       clear();
85   }
86 }
87
88
89 /// TranspositionTable::clear overwrites the entire transposition table
90 /// with zeroes. It is called whenever the table is resized, or when the
91 /// user asks the program to clear the table (from the UCI interface).
92 /// Perhaps we should also clear it when the "ucinewgame" command is recieved?
93
94 void TranspositionTable::clear() {
95
96   memset(entries, 0, size * ClusterSize * sizeof(TTEntry));
97 }
98
99
100 /// TranspositionTable::first_entry returns a pointer to the first
101 /// entry of a cluster given a position. The low 32 bits of the key
102 /// are used to get the index in the table.
103
104 inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
105
106   return entries + ((uint32_t(posKey) & (size - 1)) * ClusterSize);
107 }
108
109
110 /// TranspositionTable::store writes a new entry containing a position,
111 /// a value, a value type, a search depth, and a best move to the
112 /// transposition table. Transposition table is organized in clusters of
113 /// four TTEntry objects, and when a new entry is written, it replaces
114 /// the least valuable of the four entries in a cluster. A TTEntry t1 is
115 /// considered to be more valuable than a TTEntry t2 if t1 is from the
116 /// current search and t2 is from a previous search, or if the depth of t1
117 /// is bigger than the depth of t2. A TTEntry of type VALUE_TYPE_EVAL
118 /// never replaces another entry for the same position.
119
120 void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m) {
121
122   TTEntry *tte, *replace;
123   uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key
124
125   tte = replace = first_entry(posKey);
126   for (int i = 0; i < ClusterSize; i++, tte++)
127   {
128       if (!tte->key() || tte->key() == posKey32) // empty or overwrite old
129       {
130           // Do not overwrite when new type is VALUE_TYPE_EVAL
131           if (tte->key() && t == VALUE_TYPE_EVAL)
132               return;
133
134           if (m == MOVE_NONE)
135               m = tte->move();
136
137           *tte = TTEntry(posKey32, v, t, d, m, generation);
138           return;
139       }
140       else if (i == 0)  // replace would be a no-op in this common case
141           continue;
142
143       int c1 = (replace->generation() == generation ?  2 : 0);
144       int c2 = (tte->generation() == generation ? -2 : 0);
145       int c3 = (tte->depth() < replace->depth() ?  1 : 0);
146
147       if (c1 + c2 + c3 > 0)
148           replace = tte;
149   }
150   *replace = TTEntry(posKey32, v, t, d, m, generation);
151   writes++;
152 }
153
154
155 /// TranspositionTable::retrieve looks up the current position in the
156 /// transposition table. Returns a pointer to the TTEntry or NULL
157 /// if position is not found.
158
159 TTEntry* TranspositionTable::retrieve(const Key posKey) const {
160
161   uint32_t posKey32 = posKey >> 32;
162   TTEntry* tte = first_entry(posKey);
163
164   for (int i = 0; i < ClusterSize; i++, tte++)
165       if (tte->key() == posKey32)
166           return tte;
167
168   return NULL;
169 }
170
171
172 /// TranspositionTable::prefetch looks up the current position in the
173 /// transposition table and load it in L1/L2 cache. This is a non
174 /// blocking function and do not stalls the CPU waiting for data
175 /// to be loaded from RAM, that can be very slow. When we will
176 /// subsequently call retrieve() the TT data will be already
177 /// quickly accessible in L1/L2 CPU cache.
178
179 void TranspositionTable::prefetch(const Key posKey) const {
180
181 #if defined(_MSC_VER)
182    char* addr = (char*)first_entry(posKey);
183   _mm_prefetch(addr, _MM_HINT_T0);
184   _mm_prefetch(addr+64, _MM_HINT_T0);
185 #else
186   // We need to force an asm volatile here because gcc builtin
187   // is optimized away by Intel compiler.
188   char* addr = (char*)first_entry(posKey);
189   asm volatile("prefetcht0 %0" :: "m" (addr));
190 #endif
191 }
192
193
194 /// TranspositionTable::new_search() is called at the beginning of every new
195 /// search. It increments the "generation" variable, which is used to
196 /// distinguish transposition table entries from previous searches from
197 /// entries from the current search.
198
199 void TranspositionTable::new_search() {
200
201   generation++;
202   writes = 0;
203 }
204
205
206 /// TranspositionTable::insert_pv() is called at the end of a search
207 /// iteration, and inserts the PV back into the PV. This makes sure
208 /// the old PV moves are searched first, even if the old TT entries
209 /// have been overwritten.
210
211 void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
212
213   StateInfo st;
214   Position p(pos);
215
216   for (int i = 0; pv[i] != MOVE_NONE; i++)
217   {
218       store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i]);
219       p.do_move(pv[i], st);
220   }
221 }
222
223
224 /// TranspositionTable::extract_pv() extends a PV by adding moves from the
225 /// transposition table at the end. This should ensure that the PV is almost
226 /// always at least two plies long, which is important, because otherwise we
227 /// will often get single-move PVs when the search stops while failing high,
228 /// and a single-move PV means that we don't have a ponder move.
229
230 void TranspositionTable::extract_pv(const Position& pos, Move pv[]) {
231
232   int ply;
233   Position p(pos);
234   StateInfo st[100];
235
236   for (ply = 0; pv[ply] != MOVE_NONE; ply++)
237       p.do_move(pv[ply], st[ply]);
238
239   bool stop;
240   const TTEntry* tte;
241   for (stop = false, tte = retrieve(p.get_key());
242        tte && tte->move() != MOVE_NONE && !stop;
243        tte = retrieve(p.get_key()), ply++)
244   {
245       if (!move_is_legal(p, tte->move()))
246           break;
247       pv[ply] = tte->move();
248       p.do_move(pv[ply], st[ply]);
249       for (int j = 0; j < ply; j++)
250           if (st[j].key == p.get_key()) stop = true;
251   }
252   pv[ply] = MOVE_NONE;
253 }
254
255
256 /// TranspositionTable::full() returns the permill of all transposition table
257 /// entries which have received at least one write during the current search.
258 /// It is used to display the "info hashfull ..." information in UCI.
259
260 int TranspositionTable::full() const {
261
262   double N = double(size) * ClusterSize;
263   return int(1000 * (1 - exp(writes * log(1.0 - 1.0/N))));
264 }