| 1 |
// Copyright 2022 gRPC authors. |
| 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 |
#include <atomic> |
| 16 |
#include <cstdint> |
| 17 |
#include <fstream> |
| 18 |
#include <limits> |
| 19 |
#include <map> |
| 20 |
#include <numeric> |
| 21 |
#include <queue> |
| 22 |
#include <set> |
| 23 |
#include <string> |
| 24 |
#include <thread> |
| 25 |
#include <vector> |
| 26 |
|
| 27 |
#include <openssl/sha.h> |
| 28 |
|
| 29 |
#include "absl/memory/memory.h" |
| 30 |
#include "absl/strings/str_cat.h" |
| 31 |
#include "absl/strings/str_join.h" |
| 32 |
#include "absl/types/optional.h" |
| 33 |
#include "absl/types/variant.h" |
| 34 |
|
| 35 |
#include "src/core/ext/transport/chttp2/transport/huffsyms.h" |
| 36 |
|
| 37 |
/////////////////////////////////////////////////////////////////////////////// |
| 38 |
// SHA256 hash handling |
| 39 |
// We need strong uniqueness checks of some very long strings - so we hash |
| 40 |
// them with SHA256 and compare. |
| 41 |
struct Hash { |
| 42 |
uint8_t bytes[SHA256_DIGEST_LENGTH]; |
| 43 |
bool operator==(const Hash& other) const { |
| 44 |
return memcmp(bytes, other.bytes, SHA256_DIGEST_LENGTH) == 0; |
| 45 |
} |
| 46 |
bool operator<(const Hash& other) const { |
| 47 |
return memcmp(bytes, other.bytes, SHA256_DIGEST_LENGTH) < 0; |
| 48 |
} |
| 49 |
}; |
| 50 |
|
| 51 |
// Given a vector of ints (T), return a Hash object with the sha256 |
| 52 |
template <typename T> |
| 53 |
Hash HashVec(const std::vector<T>& v) { |
| 54 |
Hash h; |
| 55 |
SHA1(reinterpret_cast<const uint8_t*>(v.data()), v.size() * sizeof(T), |
| 56 |
h.bytes); |
| 57 |
return h; |
| 58 |
} |
| 59 |
|
| 60 |
/////////////////////////////////////////////////////////////////////////////// |
| 61 |
// BitQueue |
| 62 |
// A utility that treats a sequence of bits like a queue |
| 63 |
class BitQueue { |
| 64 |
public: |
| 65 |
BitQueue(unsigned mask, int len) : mask_(mask), len_(len) {} |
| 66 |
BitQueue() : BitQueue(0, 0) {} |
| 67 |
|
| 68 |
// Return the most significant bit (the front of the queue) |
| 69 |
int Front() const { return (mask_ >> (len_ - 1)) & 1; } |
| 70 |
// Pop one bit off the queue |
| 71 |
void Pop() { |
| 72 |
mask_ &= ~(1 << (len_ - 1)); |
| 73 |
len_--; |
| 74 |
} |
| 75 |
bool Empty() const { return len_ == 0; } |
| 76 |
int length() const { return len_; } |
| 77 |
unsigned mask() const { return mask_; } |
| 78 |
|
| 79 |
// Text representation of the queue |
| 80 |
std::string ToString() const { |
| 81 |
return absl::StrCat(absl::Hex(mask_), "/", len_); |
| 82 |
} |
| 83 |
|
| 84 |
// Comparisons so that we can use BitQueue as a key in a std::map |
| 85 |
bool operator<(const BitQueue& other) const { |
| 86 |
return std::tie(mask_, len_) < std::tie(other.mask_, other.len_); |
| 87 |
} |
| 88 |
|
| 89 |
private: |
| 90 |
// The bits |
| 91 |
unsigned mask_; |
| 92 |
// How many bits have we |
| 93 |
int len_; |
| 94 |
}; |
| 95 |
|
| 96 |
/////////////////////////////////////////////////////////////////////////////// |
| 97 |
// Symbol sets for the huffman tree |
| 98 |
|
| 99 |
// A Sym is one symbol in the tree, and the bits that we need to read to decode |
| 100 |
// that symbol. As we progress through decoding we remove bits from the symbol, |
| 101 |
// but also condense the number of symbols we're considering. |
| 102 |
struct Sym { |
| 103 |
BitQueue bits; |
| 104 |
int symbol; |
| 105 |
|
| 106 |
bool operator<(const Sym& other) const { |
| 107 |
return std::tie(bits, symbol) < std::tie(other.bits, other.symbol); |
| 108 |
} |
| 109 |
}; |
| 110 |
|
| 111 |
// A SymSet is all the symbols we're considering at some time |
| 112 |
using SymSet = std::vector<Sym>; |
| 113 |
|
| 114 |
// Debug utility to turn a SymSet into a string |
| 115 |
std::string SymSetString(const SymSet& syms) { |
| 116 |
std::vector<std::string> parts; |
| 117 |
for (const Sym& sym : syms) { |
| 118 |
parts.push_back(absl::StrCat(sym.symbol, ":", sym.bits.ToString())); |
| 119 |
} |
| 120 |
return absl::StrJoin(parts, ","); |
| 121 |
} |
| 122 |
|
| 123 |
// Initial SymSet - all the symbols [0..256] with their bits initialized from |
| 124 |
// the http2 static huffman tree. |
| 125 |
SymSet AllSyms() { |
| 126 |
SymSet syms; |
| 127 |
for (int i = 0; i < GRPC_CHTTP2_NUM_HUFFSYMS; i++) { |
| 128 |
Sym sym; |
| 129 |
sym.bits = |
| 130 |
BitQueue(grpc_chttp2_huffsyms[i].bits, grpc_chttp2_huffsyms[i].length); |
| 131 |
sym.symbol = i; |
| 132 |
syms.push_back(sym); |
| 133 |
} |
| 134 |
return syms; |
| 135 |
} |
| 136 |
|
| 137 |
// What whould we do after reading a set of bits? |
| 138 |
struct ReadActions { |
| 139 |
// Emit these symbols |
| 140 |
std::vector<int> emit; |
| 141 |
// Number of bits that were consumed by the read |
| 142 |
int consumed; |
| 143 |
// Remaining SymSet that we need to consider on the next read action |
| 144 |
SymSet remaining; |
| 145 |
}; |
| 146 |
|
| 147 |
// Given a SymSet \a pending, read through the bits in \a index and determine |
| 148 |
// what actions the decoder should take. |
| 149 |
// allow_multiple controls the behavior should we get to the last bit in pending |
| 150 |
// and hence know which symbol to emit, but we still have bits in index. |
| 151 |
// We could either start decoding the next symbol (allow_multiple == true), or |
| 152 |
// we could stop (allow_multiple == false). |
| 153 |
// If allow_multiple is true we tend to emit more per read op, but generate |
| 154 |
// bigger tables. |
| 155 |
ReadActions ActionsFor(BitQueue index, SymSet pending, bool allow_multiple) { |
| 156 |
std::vector<int> emit; |
| 157 |
int len_start = index.length(); |
| 158 |
int len_consume = len_start; |
| 159 |
|
| 160 |
// We read one bit in index at a time, so whilst we have bits... |
| 161 |
while (!index.Empty()) { |
| 162 |
SymSet next_pending; |
| 163 |
// For each symbol in the pending set |
| 164 |
for (auto sym : pending) { |
| 165 |
// If the first bit doesn't match, then that symbol is not part of our |
| 166 |
// remaining set. |
| 167 |
if (sym.bits.Front() != index.Front()) continue; |
| 168 |
sym.bits.Pop(); |
| 169 |
next_pending.push_back(sym); |
| 170 |
} |
| 171 |
switch (next_pending.size()) { |
| 172 |
case 0: |
| 173 |
// There should be no bit patterns that are undecodable. |
| 174 |
abort(); |
| 175 |
case 1: |
| 176 |
// If we have one symbol left, we need to have decoded all of it. |
| 177 |
if (!next_pending[0].bits.Empty()) abort(); |
| 178 |
// Emit that symbol |
| 179 |
emit.push_back(next_pending[0].symbol); |
| 180 |
// Track how many bits we've read. |
| 181 |
len_consume = index.length() - 1; |
| 182 |
// If we allow multiple, reprime pending and continue, otherwise stop. |
| 183 |
if (!allow_multiple) goto done; |
| 184 |
pending = AllSyms(); |
| 185 |
break; |
| 186 |
default: |
| 187 |
pending = std::move(next_pending); |
| 188 |
break; |
| 189 |
} |
| 190 |
// Finished with this bit, continue with next |
| 191 |
index.Pop(); |
| 192 |
} |
| 193 |
done: |
| 194 |
return ReadActions{std::move(emit), len_start - len_consume, pending}; |
| 195 |
} |
| 196 |
|
| 197 |
/////////////////////////////////////////////////////////////////////////////// |
| 198 |
// MatchCase |
| 199 |
// A variant that helps us bunch together related ReadActions |
| 200 |
|
| 201 |
// A Matched in a MatchCase indicates that we need to emit some number of |
| 202 |
// symbols |
| 203 |
struct Matched { |
| 204 |
// number of symbols to emit |
| 205 |
int emits; |
| 206 |
|
| 207 |
bool operator<(const Matched& other) const { return emits < other.emits; } |
| 208 |
}; |
| 209 |
|
| 210 |
// Unmatched says we didn't emit anything and we need to keep decoding |
| 211 |
struct Unmatched { |
| 212 |
SymSet syms; |
| 213 |
|
| 214 |
bool operator<(const Unmatched& other) const { return syms < other.syms; } |
| 215 |
}; |
| 216 |
|
| 217 |
// Emit end of stream |
| 218 |
struct End { |
| 219 |
bool operator<(End) const { return false; } |
| 220 |
}; |
| 221 |
|
| 222 |
using MatchCase = absl::variant<Matched, Unmatched, End>; |
| 223 |
|
| 224 |
/////////////////////////////////////////////////////////////////////////////// |
| 225 |
// Text & numeric helper functions |
| 226 |
|
| 227 |
// Given a vector of lines, indent those lines by some number of indents |
| 228 |
// (2 spaces) and return that. |
| 229 |
std::vector<std::string> IndentLines(std::vector<std::string> lines, |
| 230 |
int n = 1) { |
| 231 |
std::string indent(2 * n, ' '); |
| 232 |
for (auto& line : lines) { |
| 233 |
line = absl::StrCat(indent, line); |
| 234 |
} |
| 235 |
return lines; |
| 236 |
} |
| 237 |
|
| 238 |
// Given a snake_case_name return a PascalCaseName |
| 239 |
std::string ToPascalCase(const std::string& in) { |
| 240 |
std::string out; |
| 241 |
bool next_upper = true; |
| 242 |
for (char c : in) { |
| 243 |
if (c == '_') { |
| 244 |
next_upper = true; |
| 245 |
} else { |
| 246 |
if (next_upper) { |
| 247 |
out.push_back(toupper(c)); |
| 248 |
next_upper = false; |
| 249 |
} else { |
| 250 |
out.push_back(c); |
| 251 |
} |
| 252 |
} |
| 253 |
} |
| 254 |
return out; |
| 255 |
} |
| 256 |
|
| 257 |
// Return a uint type for some number of bits (16 -> uint16_t, 32 -> uint32_t) |
| 258 |
std::string Uint(int bits) { return absl::StrCat("uint", bits, "_t"); } |
| 259 |
|
| 260 |
// Given a maximum value, how many bits to store it in a uint |
| 261 |
int TypeBitsForMax(int max) { |
| 262 |
if (max <= 255) { |
| 263 |
return 8; |
| 264 |
} else if (max <= 65535) { |
| 265 |
return 16; |
| 266 |
} else { |
| 267 |
return 32; |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
// Combine Uint & TypeBitsForMax to make for more concise code |
| 272 |
std::string TypeForMax(int max) { return Uint(TypeBitsForMax(max)); } |
| 273 |
|
| 274 |
// How many bits are needed to encode a value |
| 275 |
int BitsForMaxValue(int x) { |
| 276 |
int n = 0; |
| 277 |
while (x >= (1 << n)) n++; |
| 278 |
return n; |
| 279 |
} |
| 280 |
|
| 281 |
/////////////////////////////////////////////////////////////////////////////// |
| 282 |
// Codegen framework |
| 283 |
// Some helpers so we don't need to generate all the code linearly, which helps |
| 284 |
// organize this a little more nicely. |
| 285 |
|
| 286 |
// An Item is our primitive for code generation, it can generate some lines |
| 287 |
// that it would like to emit - those lines are fed to a parent item that might |
| 288 |
// generate more lines or mutate the ones we return, and so on until codegen |
| 289 |
// is complete. |
| 290 |
class Item { |
| 291 |
public: |
| 292 |
virtual ~Item() = default; |
| 293 |
virtual std::vector<std::string> ToLines() const = 0; |
| 294 |
std::string ToString() const { |
| 295 |
return absl::StrCat(absl::StrJoin(ToLines(), "\n"), "\n"); |
| 296 |
} |
| 297 |
}; |
| 298 |
using ItemPtr = std::unique_ptr<Item>; |
| 299 |
|
| 300 |
// An item that emits one line (the one given as an argument!) |
| 301 |
class String : public Item { |
| 302 |
public: |
| 303 |
explicit String(std::string s) : s_(std::move(s)) {} |
| 304 |
std::vector<std::string> ToLines() const override { return {s_}; } |
| 305 |
|
| 306 |
private: |
| 307 |
std::string s_; |
| 308 |
}; |
| 309 |
|
| 310 |
// An item that returns a fixed copyright notice and autogenerated note text. |
| 311 |
class Prelude final : public Item { |
| 312 |
public: |
| 313 |
std::vector<std::string> ToLines() const { |
| 314 |
return { |
| 315 |
"// Copyright 2022 gRPC authors.", |
| 316 |
"//", |
| 317 |
"// Licensed under the Apache License, Version 2.0 (the " |
| 318 |
"\"License\");", |
| 319 |
"// you may not use this file except in compliance with the License.", |
| 320 |
"// You may obtain a copy of the License at", |
| 321 |
"//", |
| 322 |
"// http://www.apache.org/licenses/LICENSE-2.0", |
| 323 |
"//", |
| 324 |
"// Unless required by applicable law or agreed to in writing, " |
| 325 |
"software", |
| 326 |
"// distributed under the License is distributed on an \"AS IS\" " |
| 327 |
"BASIS,", |
| 328 |
"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or " |
| 329 |
"implied.", |
| 330 |
"// See the License for the specific language governing permissions " |
| 331 |
"and", |
| 332 |
"// limitations under the License.", |
| 333 |
"", |
| 334 |
std::string(80, '/'), |
| 335 |
"// This file is autogenerated: see " |
| 336 |
"tools/codegen/core/gen_huffman_decompressor.cc", |
| 337 |
""}; |
| 338 |
} |
| 339 |
}; |
| 340 |
|
| 341 |
class Switch; |
| 342 |
|
| 343 |
// A Sink is an Item that we can add more Items to. |
| 344 |
// At codegen time it calls each of its children in turn and concatenates |
| 345 |
// their results together. |
| 346 |
class Sink : public Item { |
| 347 |
public: |
| 348 |
std::vector<std::string> ToLines() const override { |
| 349 |
std::vector<std::string> lines; |
| 350 |
for (const auto& item : children_) { |
| 351 |
for (const auto& line : item->ToLines()) { |
| 352 |
lines.push_back(line); |
| 353 |
} |
| 354 |
} |
| 355 |
return lines; |
| 356 |
} |
| 357 |
|
| 358 |
// Add one string to our output. |
| 359 |
void Add(std::string s) { |
| 360 |
children_.push_back(std::make_unique<String>(std::move(s))); |
| 361 |
} |
| 362 |
|
| 363 |
// Add an item of type T to our output (constructing it with args). |
| 364 |
template <typename T, typename... Args> |
| 365 |
T* Add(Args&&... args) { |
| 366 |
auto v = std::make_unique<T>(std::forward<Args>(args)...); |
| 367 |
auto* r = v.get(); |
| 368 |
children_.push_back(std::move(v)); |
| 369 |
return r; |
| 370 |
} |
| 371 |
|
| 372 |
private: |
| 373 |
std::vector<ItemPtr> children_; |
| 374 |
}; |
| 375 |
|
| 376 |
// A sink that indents its lines by one indent (2 spaces) |
| 377 |
class Indent : public Sink { |
| 378 |
public: |
| 379 |
std::vector<std::string> ToLines() const override { |
| 380 |
return IndentLines(Sink::ToLines()); |
| 381 |
} |
| 382 |
}; |
| 383 |
|
| 384 |
// A Sink that wraps its lines in a while block |
| 385 |
class While : public Sink { |
| 386 |
public: |
| 387 |
explicit While(std::string cond) : cond_(std::move(cond)) {} |
| 388 |
std::vector<std::string> ToLines() const override { |
| 389 |
std::vector<std::string> lines; |
| 390 |
lines.push_back(absl::StrCat("while (", cond_, ") {")); |
| 391 |
for (const auto& line : IndentLines(Sink::ToLines())) { |
| 392 |
lines.push_back(line); |
| 393 |
} |
| 394 |
lines.push_back("}"); |
| 395 |
return lines; |
| 396 |
} |
| 397 |
|
| 398 |
private: |
| 399 |
std::string cond_; |
| 400 |
}; |
| 401 |
|
| 402 |
// A switch statement. |
| 403 |
// Cases can be modified by calling the Case member. |
| 404 |
// Identical cases are collapsed into 'case X: case Y:' type blocks. |
| 405 |
class Switch : public Item { |
| 406 |
public: |
| 407 |
// \a cond is the condition to place at the head of the switch statement. |
| 408 |
// eg. "switch (cond) {". |
| 409 |
explicit Switch(std::string cond) : cond_(std::move(cond)) {} |
| 410 |
std::vector<std::string> ToLines() const override { |
| 411 |
std::map<std::string, std::vector<std::string>> reverse_map; |
| 412 |
for (const auto& kv : cases_) { |
| 413 |
reverse_map[kv.second.ToString()].push_back(kv.first); |
| 414 |
} |
| 415 |
std::vector<std::string> lines; |
| 416 |
lines.push_back(absl::StrCat("switch (", cond_, ") {")); |
| 417 |
for (const auto& kv : reverse_map) { |
| 418 |
for (const auto& cond : kv.second) { |
| 419 |
lines.push_back(absl::StrCat(" case ", cond, ":")); |
| 420 |
} |
| 421 |
lines.back().append(" {"); |
| 422 |
for (const auto& case_line : |
| 423 |
IndentLines(cases_.find(kv.second[0])->second.ToLines(), 2)) { |
| 424 |
lines.push_back(case_line); |
| 425 |
} |
| 426 |
lines.push_back(" }"); |
| 427 |
} |
| 428 |
lines.push_back("}"); |
| 429 |
return lines; |
| 430 |
} |
| 431 |
|
| 432 |
Sink* Case(std::string cond) { return &cases_[cond]; } |
| 433 |
|
| 434 |
private: |
| 435 |
std::string cond_; |
| 436 |
std::map<std::string, Sink> cases_; |
| 437 |
}; |
| 438 |
|
| 439 |
/////////////////////////////////////////////////////////////////////////////// |
| 440 |
// BuildCtx declaration |
| 441 |
// Shared state for one code gen attempt |
| 442 |
|
| 443 |
class TableBuilder; |
| 444 |
class FunMaker; |
| 445 |
|
| 446 |
class BuildCtx { |
| 447 |
public: |
| 448 |
BuildCtx(std::vector<int> max_bits_for_depth, Sink* global_fns, |
| 449 |
Sink* global_decls, Sink* global_values, FunMaker* fun_maker) |
| 450 |
: max_bits_for_depth_(std::move(max_bits_for_depth)), |
| 451 |
global_fns_(global_fns), |
| 452 |
global_decls_(global_decls), |
| 453 |
global_values_(global_values), |
| 454 |
fun_maker_(fun_maker) {} |
| 455 |
|
| 456 |
void AddStep(SymSet start_syms, int num_bits, bool is_top, bool refill, |
| 457 |
int depth, Sink* out); |
| 458 |
void AddMatchBody(TableBuilder* table_builder, std::string index, |
| 459 |
std::string ofs, const MatchCase& match_case, bool is_top, |
| 460 |
bool refill, int depth, Sink* out); |
| 461 |
void AddDone(SymSet start_syms, int num_bits, bool all_ones_so_far, |
| 462 |
Sink* out); |
| 463 |
|
| 464 |
int NewId() { return next_id_++; } |
| 465 |
int MaxBitsForTop() const { return max_bits_for_depth_[0]; } |
| 466 |
|
| 467 |
absl::optional<std::string> PreviousNameForArtifact(std::string proposed_name, |
| 468 |
Hash hash) { |
| 469 |
auto it = arrays_.find(hash); |
| 470 |
if (it == arrays_.end()) { |
| 471 |
arrays_.emplace(hash, proposed_name); |
| 472 |
return absl::nullopt; |
| 473 |
} |
| 474 |
return it->second; |
| 475 |
} |
| 476 |
|
| 477 |
Sink* global_fns() const { return global_fns_; } |
| 478 |
Sink* global_decls() const { return global_decls_; } |
| 479 |
Sink* global_values() const { return global_values_; } |
| 480 |
|
| 481 |
private: |
| 482 |
const std::vector<int> max_bits_for_depth_; |
| 483 |
std::map<Hash, std::string> arrays_; |
| 484 |
int next_id_ = 1; |
| 485 |
Sink* const global_fns_; |
| 486 |
Sink* const global_decls_; |
| 487 |
Sink* const global_values_; |
| 488 |
FunMaker* const fun_maker_; |
| 489 |
}; |
| 490 |
|
| 491 |
/////////////////////////////////////////////////////////////////////////////// |
| 492 |
// TableBuilder |
| 493 |
// All our magic for building decode tables. |
| 494 |
// We have three kinds of tables to generate: |
| 495 |
// 1. op tables that translate a bit sequence to which decode case we should |
| 496 |
// execute (and arguments to it), and |
| 497 |
// 2. emit tables that translate an index given by the op table and tell us |
| 498 |
// which symbols to emit |
| 499 |
// Op table format |
| 500 |
// Our opcodes contain an offset into an emit table, a number of bits consumed |
| 501 |
// and an operation. The consumed bits are how many of the presented to us bits |
| 502 |
// we actually took. The operation tells whether to emit some symbols (and how |
| 503 |
// many) or to keep decoding. |
| 504 |
// Optimization 1: |
| 505 |
// op tables are essentially dense maps of bits -> opcode, and it turns out |
| 506 |
// that *many* of the opcodes repeat across index bits for some of our tables |
| 507 |
// so for those we split the table into two levels: first level indexes into |
| 508 |
// a child table, and the child table contains the deduped opcodes. |
| 509 |
// Optimization 2: |
| 510 |
// Emit tables are a bit list of uint8_ts, and are indexed into by the op |
| 511 |
// table (with an offset and length) - since many symbols get repeated, we try |
| 512 |
// to overlay the symbols in the emit table to reduce the size. |
| 513 |
// Optimization 3: |
| 514 |
// We shard the table into some number of slices and use the top bits of the |
| 515 |
// incoming lookup to select the shard. This tends to allow us to use smaller |
| 516 |
// types to represent the table, saving on footprint. |
| 517 |
|
| 518 |
class TableBuilder { |
| 519 |
public: |
| 520 |
explicit TableBuilder(BuildCtx* ctx) : ctx_(ctx), id_(ctx->NewId()) {} |
| 521 |
|
| 522 |
// Append one case to the table |
| 523 |
void Add(int match_case, std::vector<uint8_t> emit, int consumed_bits) { |
| 524 |
elems_.push_back({match_case, std::move(emit), consumed_bits}); |
| 525 |
max_consumed_bits_ = std::max(max_consumed_bits_, consumed_bits); |
| 526 |
max_match_case_ = std::max(max_match_case_, match_case); |
| 527 |
} |
| 528 |
|
| 529 |
// Build the table |
| 530 |
void Build() const { |
| 531 |
Choose()->Build(this, BitsForMaxValue(elems_.size() - 1)); |
| 532 |
} |
| 533 |
|
| 534 |
// Generate a call to the accessor function for the emit table |
| 535 |
std::string EmitAccessor(std::string index, std::string offset) { |
| 536 |
return absl::StrCat("GetEmit", id_, "(", index, ", ", offset, ")"); |
| 537 |
} |
| 538 |
|
| 539 |
// Generate a call to the accessor function for the op table |
| 540 |
std::string OpAccessor(std::string index) { |
| 541 |
return absl::StrCat("GetOp", id_, "(", index, ")"); |
| 542 |
} |
| 543 |
|
| 544 |
int ConsumeBits() const { return BitsForMaxValue(max_consumed_bits_); } |
| 545 |
int MatchBits() const { return BitsForMaxValue(max_match_case_); } |
| 546 |
|
| 547 |
private: |
| 548 |
// One element in the op table. |
| 549 |
struct Elem { |
| 550 |
int match_case; |
| 551 |
std::vector<uint8_t> emit; |
| 552 |
int consumed_bits; |
| 553 |
}; |
| 554 |
|
| 555 |
// A nested slice is one slice of a table using two level lookup |
| 556 |
// - i.e. we look at an outer table to get an index into the inner table, |
| 557 |
// and then fetch the result from there. |
| 558 |
struct NestedSlice { |
| 559 |
std::vector<uint8_t> emit; |
| 560 |
std::vector<uint64_t> inner; |
| 561 |
std::vector<int> outer; |
| 562 |
|
| 563 |
// Various sizes return number of bits to be generated |
| 564 |
|
| 565 |
size_t InnerSize() const { |
| 566 |
return inner.size() * |
| 567 |
TypeBitsForMax(*std::max_element(inner.begin(), inner.end())); |
| 568 |
} |
| 569 |
|
| 570 |
size_t OuterSize() const { |
| 571 |
return outer.size() * |
| 572 |
TypeBitsForMax(*std::max_element(outer.begin(), outer.end())); |
| 573 |
} |
| 574 |
|
| 575 |
size_t EmitSize() const { return emit.size() * 8; } |
| 576 |
}; |
| 577 |
|
| 578 |
// A slice is one part of a larger table. |
| 579 |
struct Slice { |
| 580 |
std::vector<uint8_t> emit; |
| 581 |
std::vector<uint64_t> ops; |
| 582 |
|
| 583 |
// Various sizes return number of bits to be generated |
| 584 |
|
| 585 |
size_t OpsSize() const { |
| 586 |
return ops.size() * |
| 587 |
TypeBitsForMax(*std::max_element(ops.begin(), ops.end())); |
| 588 |
} |
| 589 |
|
| 590 |
size_t EmitSize() const { return emit.size() * 8; } |
| 591 |
|
| 592 |
// Given a vector of symbols to emit, return the offset into the emit table |
| 593 |
// that they're at (adding them to the emit table if necessary). |
| 594 |
int OffsetOf(const std::vector<uint8_t>& x) { |
| 595 |
if (x.empty()) return 0; |
| 596 |
auto r = std::search(emit.begin(), emit.end(), x.begin(), x.end()); |
| 597 |
if (r == emit.end()) { |
| 598 |
// look for a partial match @ end |
| 599 |
for (size_t check_len = x.size() - 1; check_len > 0; check_len--) { |
| 600 |
if (emit.size() < check_len) continue; |
| 601 |
bool matches = true; |
| 602 |
for (size_t i = 0; matches && i < check_len; i++) { |
| 603 |
if (emit[emit.size() - check_len + i] != x[i]) matches = false; |
| 604 |
} |
| 605 |
if (matches) { |
| 606 |
int offset = emit.size() - check_len; |
| 607 |
for (size_t i = check_len; i < x.size(); i++) { |
| 608 |
emit.push_back(x[i]); |
| 609 |
} |
| 610 |
return offset; |
| 611 |
} |
| 612 |
} |
| 613 |
// add new |
| 614 |
int result = emit.size(); |
| 615 |
for (auto v : x) emit.push_back(v); |
| 616 |
return result; |
| 617 |
} |
| 618 |
return r - emit.begin(); |
| 619 |
} |
| 620 |
|
| 621 |
// Convert this slice to a nested slice. |
| 622 |
NestedSlice MakeNestedSlice() const { |
| 623 |
NestedSlice result; |
| 624 |
result.emit = emit; |
| 625 |
std::map<uint64_t, int> op_to_inner; |
| 626 |
for (auto v : ops) { |
| 627 |
auto it = op_to_inner.find(v); |
| 628 |
if (it == op_to_inner.end()) { |
| 629 |
it = op_to_inner.emplace(v, op_to_inner.size()).first; |
| 630 |
result.inner.push_back(v); |
| 631 |
} |
| 632 |
result.outer.push_back(it->second); |
| 633 |
} |
| 634 |
return result; |
| 635 |
} |
| 636 |
}; |
| 637 |
|
| 638 |
// An EncodeOption is a potential way of encoding a table. |
| 639 |
struct EncodeOption { |
| 640 |
// Overall size (in bits) of the table encoding |
| 641 |
virtual size_t Size() const = 0; |
| 642 |
// Generate the code |
| 643 |
virtual void Build(const TableBuilder* builder, int op_bits) const = 0; |
| 644 |
virtual ~EncodeOption() {} |
| 645 |
}; |
| 646 |
|
| 647 |
// NestedTable is a table that uses two level lookup for each slice |
| 648 |
struct NestedTable : public EncodeOption { |
| 649 |
std::vector<NestedSlice> slices; |
| 650 |
int slice_bits; |
| 651 |
size_t Size() const override { |
| 652 |
size_t sum = 0; |
| 653 |
std::vector<Hash> h_emit; |
| 654 |
std::vector<Hash> h_inner; |
| 655 |
std::vector<Hash> h_outer; |
| 656 |
for (size_t i = 0; i < slices.size(); i++) { |
| 657 |
h_emit.push_back(HashVec(slices[i].emit)); |
| 658 |
h_inner.push_back(HashVec(slices[i].inner)); |
| 659 |
h_outer.push_back(HashVec(slices[i].outer)); |
| 660 |
} |
| 661 |
std::set<Hash> seen; |
| 662 |
for (size_t i = 0; i < slices.size(); i++) { |
| 663 |
// Try to account for deduplication in the size calculation. |
| 664 |
if (seen.count(h_emit[i]) == 0) sum += slices[i].EmitSize(); |
| 665 |
if (seen.count(h_outer[i]) == 0) sum += slices[i].OuterSize(); |
| 666 |
if (seen.count(h_inner[i]) == 0) sum += slices[i].OuterSize(); |
| 667 |
seen.insert(h_emit[i]); |
| 668 |
seen.insert(h_outer[i]); |
| 669 |
seen.insert(h_inner[i]); |
| 670 |
} |
| 671 |
if (slice_bits != 0) sum += 3 * 64 * slices.size(); |
| 672 |
return sum; |
| 673 |
} |
| 674 |
void Build(const TableBuilder* builder, int op_bits) const override { |
| 675 |
Sink* const global_fns = builder->ctx_->global_fns(); |
| 676 |
Sink* const global_decls = builder->ctx_->global_decls(); |
| 677 |
Sink* const global_values = builder->ctx_->global_values(); |
| 678 |
const int id = builder->id_; |
| 679 |
std::vector<std::string> lines; |
| 680 |
const uint64_t max_inner = MaxInner(); |
| 681 |
const uint64_t max_outer = MaxOuter(); |
| 682 |
std::vector<std::string> emit_names; |
| 683 |
std::vector<std::string> inner_names; |
| 684 |
std::vector<std::string> outer_names; |
| 685 |
for (size_t i = 0; i < slices.size(); i++) { |
| 686 |
emit_names.push_back(builder->GenArray( |
| 687 |
absl::StrCat("table", id, "_", i, "_emit"), "uint8_t", |
| 688 |
slices[i].emit, true, global_decls, global_values)); |
| 689 |
inner_names.push_back(builder->GenArray( |
| 690 |
absl::StrCat("table", id, "_", i, "_inner"), TypeForMax(max_inner), |
| 691 |
slices[i].inner, true, global_decls, global_values)); |
| 692 |
outer_names.push_back(builder->GenArray( |
| 693 |
absl::StrCat("table", id, "_", i, "_outer"), TypeForMax(max_outer), |
| 694 |
slices[i].outer, false, global_decls, global_values)); |
| 695 |
} |
| 696 |
if (slice_bits == 0) { |
| 697 |
global_fns->Add(absl::StrCat("static inline uint64_t GetOp", id, |
| 698 |
"(size_t i) { return ", inner_names[0], |
| 699 |
"[", outer_names[0], "[i]]; }")); |
| 700 |
global_fns->Add(absl::StrCat("static inline uint64_t GetEmit", id, |
| 701 |
"(size_t, size_t emit) { return ", |
| 702 |
emit_names[0], "[emit]; }")); |
| 703 |
} else { |
| 704 |
GenCompound(id, emit_names, "emit", "uint8_t", global_decls, |
| 705 |
global_values); |
| 706 |
GenCompound(id, inner_names, "inner", TypeForMax(max_inner), |
| 707 |
global_decls, global_values); |
| 708 |
GenCompound(id, outer_names, "outer", TypeForMax(max_outer), |
| 709 |
global_decls, global_values); |
| 710 |
global_fns->Add(absl::StrCat( |
| 711 |
"static inline uint64_t GetOp", id, "(size_t i) { return table", id, |
| 712 |
"_inner_[i >> ", op_bits - slice_bits, "][table", id, |
| 713 |
"_outer_[i >> ", op_bits - slice_bits, "][i & 0x", |
| 714 |
absl::Hex((1 << (op_bits - slice_bits)) - 1), "]]; }")); |
| 715 |
global_fns->Add(absl::StrCat("static inline uint64_t GetEmit", id, |
| 716 |
"(size_t i, size_t emit) { return table", |
| 717 |
id, "_emit_[i >> ", op_bits - slice_bits, |
| 718 |
"][emit]; }")); |
| 719 |
} |
| 720 |
} |
| 721 |
uint64_t MaxInner() const { |
| 722 |
uint64_t max_inner = 0; |
| 723 |
for (size_t i = 0; i < slices.size(); i++) { |
| 724 |
max_inner = std::max( |
| 725 |
max_inner, |
| 726 |
*std::max_element(slices[i].inner.begin(), slices[i].inner.end())); |
| 727 |
} |
| 728 |
return max_inner; |
| 729 |
} |
| 730 |
int MaxOuter() const { |
| 731 |
int max_outer = 0; |
| 732 |
for (size_t i = 0; i < slices.size(); i++) { |
| 733 |
max_outer = std::max( |
| 734 |
max_outer, |
| 735 |
*std::max_element(slices[i].outer.begin(), slices[i].outer.end())); |
| 736 |
} |
| 737 |
return max_outer; |
| 738 |
} |
| 739 |
}; |
| 740 |
|
| 741 |
// Encoding that uses single level lookup for each slice. |
| 742 |
struct Table : public EncodeOption { |
| 743 |
std::vector<Slice> slices; |
| 744 |
int slice_bits; |
| 745 |
size_t Size() const override { |
| 746 |
size_t sum = 0; |
| 747 |
std::vector<Hash> h_emit; |
| 748 |
std::vector<Hash> h_ops; |
| 749 |
for (size_t i = 0; i < slices.size(); i++) { |
| 750 |
h_emit.push_back(HashVec(slices[i].emit)); |
| 751 |
h_ops.push_back(HashVec(slices[i].ops)); |
| 752 |
} |
| 753 |
std::set<Hash> seen; |
| 754 |
for (size_t i = 0; i < slices.size(); i++) { |
| 755 |
if (seen.count(h_emit[i]) == 0) sum += slices[i].EmitSize(); |
| 756 |
if (seen.count(h_ops[i]) == 0) sum += slices[i].OpsSize(); |
| 757 |
seen.insert(h_emit[i]); |
| 758 |
seen.insert(h_ops[i]); |
| 759 |
} |
| 760 |
return sum + 3 * 64 * slices.size(); |
| 761 |
} |
| 762 |
void Build(const TableBuilder* builder, int op_bits) const override { |
| 763 |
Sink* const global_fns = builder->ctx_->global_fns(); |
| 764 |
Sink* const global_decls = builder->ctx_->global_decls(); |
| 765 |
Sink* const global_values = builder->ctx_->global_values(); |
| 766 |
uint64_t max_op = MaxOp(); |
| 767 |
const int id = builder->id_; |
| 768 |
std::vector<std::string> emit_names; |
| 769 |
std::vector<std::string> ops_names; |
| 770 |
for (size_t i = 0; i < slices.size(); i++) { |
| 771 |
emit_names.push_back(builder->GenArray( |
| 772 |
absl::StrCat("table", id, "_", i, "_emit"), "uint8_t", |
| 773 |
slices[i].emit, true, global_decls, global_values)); |
| 774 |
ops_names.push_back(builder->GenArray( |
| 775 |
absl::StrCat("table", id, "_", i, "_ops"), TypeForMax(max_op), |
| 776 |
slices[i].ops, true, global_decls, global_values)); |
| 777 |
} |
| 778 |
if (slice_bits == 0) { |
| 779 |
global_fns->Add(absl::StrCat("static inline uint64_t GetOp", id, |
| 780 |
"(size_t i) { return ", ops_names[0], |
| 781 |
"[i]; }")); |
| 782 |
global_fns->Add(absl::StrCat("static inline uint64_t GetEmit", id, |
| 783 |
"(size_t, size_t emit) { return ", |
| 784 |
emit_names[0], "[emit]; }")); |
| 785 |
} else { |
| 786 |
GenCompound(id, emit_names, "emit", "uint8_t", global_decls, |
| 787 |
global_values); |
| 788 |
GenCompound(id, ops_names, "ops", TypeForMax(max_op), global_decls, |
| 789 |
global_values); |
| 790 |
global_fns->Add(absl::StrCat( |
| 791 |
"static inline uint64_t GetOp", id, "(size_t i) { return table", id, |
| 792 |
"_ops_[i >> ", op_bits - slice_bits, "][i & 0x", |
| 793 |
absl::Hex((1 << (op_bits - slice_bits)) - 1), "]; }")); |
| 794 |
global_fns->Add(absl::StrCat("static inline uint64_t GetEmit", id, |
| 795 |
"(size_t i, size_t emit) { return table", |
| 796 |
id, "_emit_[i >> ", op_bits - slice_bits, |
| 797 |
"][emit]; }")); |
| 798 |
} |
| 799 |
} |
| 800 |
uint64_t MaxOp() const { |
| 801 |
uint64_t max_op = 0; |
| 802 |
for (size_t i = 0; i < slices.size(); i++) { |
| 803 |
max_op = std::max(max_op, *std::max_element(slices[i].ops.begin(), |
| 804 |
slices[i].ops.end())); |
| 805 |
} |
| 806 |
return max_op; |
| 807 |
} |
| 808 |
// Convert to a two-level lookup |
| 809 |
std::unique_ptr<NestedTable> MakeNestedTable() { |
| 810 |
std::unique_ptr<NestedTable> result(new NestedTable); |
| 811 |
result->slice_bits = slice_bits; |
| 812 |
for (const auto& slice : slices) { |
| 813 |
result->slices.push_back(slice.MakeNestedSlice()); |
| 814 |
} |
| 815 |
return result; |
| 816 |
} |
| 817 |
}; |
| 818 |
|
| 819 |
// Given a number of slices (2**slice_bits), generate a table that uses a |
| 820 |
// single level lookup for each slice based on our input. |
| 821 |
std::unique_ptr<Table> MakeTable(size_t slice_bits) const { |
| 822 |
std::unique_ptr<Table> table = std::make_unique<Table>(); |
| 823 |
int slices = 1 << slice_bits; |
| 824 |
table->slices.resize(slices); |
| 825 |
table->slice_bits = slice_bits; |
| 826 |
const int pack_consume_bits = ConsumeBits(); |
| 827 |
const int pack_match_bits = MatchBits(); |
| 828 |
for (size_t i = 0; i < slices; i++) { |
| 829 |
auto& slice = table->slices[i]; |
| 830 |
for (size_t j = 0; j < elems_.size() / slices; j++) { |
| 831 |
const auto& elem = elems_[i * elems_.size() / slices + j]; |
| 832 |
slice.ops.push_back(elem.consumed_bits | |
| 833 |
(elem.match_case << pack_consume_bits) | |
| 834 |
(slice.OffsetOf(elem.emit) |
| 835 |
<< (pack_consume_bits + pack_match_bits))); |
| 836 |
} |
| 837 |
} |
| 838 |
return table; |
| 839 |
} |
| 840 |
|
| 841 |
// Helper to generate a compound table (an array of arrays) |
| 842 |
static void GenCompound(int id, std::vector<std::string> names, |
| 843 |
std::string ext, std::string type, Sink* global_decls, |
| 844 |
Sink* global_values) { |
| 845 |
global_decls->Add(absl::StrCat("static const ", type, "* const table", id, |
| 846 |
"_", ext, "_[", names.size(), "];")); |
| 847 |
global_values->Add(absl::StrCat("const ", type, |
| 848 |
"* const HuffDecoderCommon::table", id, "_", |
| 849 |
ext, "_[", names.size(), "] = {")); |
| 850 |
for (const std::string& name : names) { |
| 851 |
global_values->Add(absl::StrCat(" ", name, ",")); |
| 852 |
} |
| 853 |
global_values->Add("};"); |
| 854 |
} |
| 855 |
|
| 856 |
// Helper to generate an array of values |
| 857 |
template <typename T> |
| 858 |
std::string GenArray(std::string name, std::string type, |
| 859 |
const std::vector<T>& values, bool hex, |
| 860 |
Sink* global_decls, Sink* global_values) const { |
| 861 |
auto previous_name = ctx_->PreviousNameForArtifact(name, HashVec(values)); |
| 862 |
if (previous_name.has_value()) { |
| 863 |
return absl::StrCat(*previous_name, "_"); |
| 864 |
} |
| 865 |
std::vector<std::string> elems; |
| 866 |
elems.reserve(values.size()); |
| 867 |
for (const auto& elem : values) { |
| 868 |
if (hex) { |
| 869 |
if (type == "uint8_t") { |
| 870 |
elems.push_back(absl::StrCat("0x", absl::Hex(elem, absl::kZeroPad2))); |
| 871 |
} else if (type == "uint16_t") { |
| 872 |
elems.push_back(absl::StrCat("0x", absl::Hex(elem, absl::kZeroPad4))); |
| 873 |
} else { |
| 874 |
elems.push_back(absl::StrCat("0x", absl::Hex(elem, absl::kZeroPad8))); |
| 875 |
} |
| 876 |
} else { |
| 877 |
elems.push_back(absl::StrCat(elem)); |
| 878 |
} |
| 879 |
} |
| 880 |
std::string data = absl::StrJoin(elems, ", "); |
| 881 |
global_decls->Add(absl::StrCat("static const ", type, " ", name, "_[", |
| 882 |
values.size(), "];")); |
| 883 |
global_values->Add(absl::StrCat("const ", type, " HuffDecoderCommon::", |
| 884 |
name, "_[", values.size(), "] = {")); |
| 885 |
global_values->Add(absl::StrCat(" ", data)); |
| 886 |
global_values->Add("};"); |
| 887 |
return absl::StrCat(name, "_"); |
| 888 |
} |
| 889 |
|
| 890 |
// Choose an encoding for this set of tables. |
| 891 |
// We try all available values for slice count and choose the one that gives |
| 892 |
// the smallest footprint. |
| 893 |
std::unique_ptr<EncodeOption> Choose() const { |
| 894 |
std::unique_ptr<EncodeOption> chosen; |
| 895 |
size_t best_size = std::numeric_limits<size_t>::max(); |
| 896 |
for (size_t slice_bits = 0; (1 << slice_bits) < elems_.size(); |
| 897 |
slice_bits++) { |
| 898 |
auto raw = MakeTable(slice_bits); |
| 899 |
size_t raw_size = raw->Size(); |
| 900 |
auto nested = raw->MakeNestedTable(); |
| 901 |
size_t nested_size = nested->Size(); |
| 902 |
if (raw_size < best_size) { |
| 903 |
chosen = std::move(raw); |
| 904 |
best_size = raw_size; |
| 905 |
} |
| 906 |
if (nested_size < best_size) { |
| 907 |
chosen = std::move(nested); |
| 908 |
best_size = nested_size; |
| 909 |
} |
| 910 |
} |
| 911 |
return chosen; |
| 912 |
} |
| 913 |
|
| 914 |
BuildCtx* const ctx_; |
| 915 |
std::vector<Elem> elems_; |
| 916 |
int max_consumed_bits_ = 0; |
| 917 |
int max_match_case_ = 0; |
| 918 |
const int id_; |
| 919 |
}; |
| 920 |
|
| 921 |
/////////////////////////////////////////////////////////////////////////////// |
| 922 |
// FunMaker |
| 923 |
// Handles generating the code for various functions. |
| 924 |
|
| 925 |
class FunMaker { |
| 926 |
public: |
| 927 |
explicit FunMaker(Sink* sink) : sink_(sink) {} |
| 928 |
|
| 929 |
// Generate a refill function - that ensures the incoming bitmask has enough |
| 930 |
// bits for the next step. |
| 931 |
std::string RefillTo(int n) { |
| 932 |
if (have_refills_.count(n) == 0) { |
| 933 |
have_refills_.insert(n); |
| 934 |
auto fn = NewFun(absl::StrCat("RefillTo", n), "bool"); |
| 935 |
auto s = fn->Add<Switch>("buffer_len_"); |
| 936 |
for (int i = 0; i < n; i++) { |
| 937 |
auto c = s->Case(absl::StrCat(i)); |
| 938 |
const int bytes_needed = (n - i + 7) / 8; |
| 939 |
c->Add(absl::StrCat("return ", ReadBytes(bytes_needed), ";")); |
| 940 |
} |
| 941 |
fn->Add("return true;"); |
| 942 |
} |
| 943 |
return absl::StrCat("RefillTo", n, "()"); |
| 944 |
} |
| 945 |
|
| 946 |
// At callsite, generate a call to a new function with base name |
| 947 |
// base_name (new functions get a suffix of how many instances of base_name |
| 948 |
// there have been). |
| 949 |
// Return a sink to fill in the body of the new function. |
| 950 |
Sink* CallNewFun(std::string base_name, Sink* callsite) { |
| 951 |
std::string name = absl::StrCat(base_name, have_funs_[base_name]++); |
| 952 |
callsite->Add(absl::StrCat(name, "();")); |
| 953 |
return NewFun(name, "void"); |
| 954 |
} |
| 955 |
|
| 956 |
private: |
| 957 |
Sink* NewFun(std::string name, std::string returns) { |
| 958 |
sink_->Add(absl::StrCat(returns, " ", name, "() {")); |
| 959 |
auto fn = sink_->Add<Indent>(); |
| 960 |
sink_->Add("}"); |
| 961 |
return fn; |
| 962 |
} |
| 963 |
|
| 964 |
// Bring in some number of bytes from the input stream to our current read |
| 965 |
// bits. |
| 966 |
std::string ReadBytes(int bytes_needed) { |
| 967 |
if (have_reads_.count(bytes_needed) == 0) { |
| 968 |
have_reads_.insert(bytes_needed); |
| 969 |
auto fn = NewFun(absl::StrCat("Read", bytes_needed), "bool"); |
| 970 |
fn->Add(absl::StrCat("if (end_ - begin_ < ", bytes_needed, |
| 971 |
") return false;")); |
| 972 |
fn->Add(absl::StrCat("buffer_ <<= ", 8 * bytes_needed, ";")); |
| 973 |
for (int i = 0; i < bytes_needed; i++) { |
| 974 |
fn->Add(absl::StrCat("buffer_ |= static_cast<uint64_t>(*begin_++) << ", |
| 975 |
8 * (bytes_needed - i - 1), ";")); |
| 976 |
} |
| 977 |
fn->Add(absl::StrCat("buffer_len_ += ", 8 * bytes_needed, ";")); |
| 978 |
fn->Add("return true;"); |
| 979 |
} |
| 980 |
return absl::StrCat("Read", bytes_needed, "()"); |
| 981 |
} |
| 982 |
|
| 983 |
std::set<int> have_refills_; |
| 984 |
std::set<int> have_reads_; |
| 985 |
std::map<std::string, int> have_funs_; |
| 986 |
Sink* sink_; |
| 987 |
}; |
| 988 |
|
| 989 |
/////////////////////////////////////////////////////////////////////////////// |
| 990 |
// BuildCtx implementation |
| 991 |
|
| 992 |
void BuildCtx::AddDone(SymSet start_syms, int num_bits, bool all_ones_so_far, |
| 993 |
Sink* out) { |
| 994 |
out->Add("done_ = true;"); |
| 995 |
if (num_bits == 1) { |
| 996 |
if (!all_ones_so_far) out->Add("ok_ = false;"); |
| 997 |
return; |
| 998 |
} |
| 999 |
// we must have 0 < buffer_len_ < num_bits |
| 1000 |
auto s = out->Add<Switch>("buffer_len_"); |
| 1001 |
auto c0 = s->Case("0"); |
| 1002 |
if (!all_ones_so_far) c0->Add("ok_ = false;"); |
| 1003 |
c0->Add("return;"); |
| 1004 |
for (int i = 1; i < num_bits; i++) { |
| 1005 |
auto c = s->Case(absl::StrCat(i)); |
| 1006 |
SymSet maybe; |
| 1007 |
for (auto sym : start_syms) { |
| 1008 |
if (sym.bits.length() > i) continue; |
| 1009 |
maybe.push_back(sym); |
| 1010 |
} |
| 1011 |
if (maybe.empty()) { |
| 1012 |
if (all_ones_so_far) { |
| 1013 |
c->Add("ok_ = (buffer_ & ((1<<buffer_len_)-1)) == (1<<buffer_len_)-1;"); |
| 1014 |
} else { |
| 1015 |
c->Add("ok_ = false;"); |
| 1016 |
} |
| 1017 |
c->Add("return;"); |
| 1018 |
continue; |
| 1019 |
} |
| 1020 |
TableBuilder table_builder(this); |
| 1021 |
enum Cases { |
| 1022 |
kNoEmitOk, |
| 1023 |
kFail, |
| 1024 |
kEmitOk, |
| 1025 |
}; |
| 1026 |
for (size_t n = 0; n < (1 << i); n++) { |
| 1027 |
if (all_ones_so_far && n == (1 << i) - 1) { |
| 1028 |
table_builder.Add(kNoEmitOk, {}, 0); |
| 1029 |
goto next; |
| 1030 |
} |
| 1031 |
for (auto sym : maybe) { |
| 1032 |
if ((n >> (i - sym.bits.length())) == sym.bits.mask()) { |
| 1033 |
for (int j = 0; j < (i - sym.bits.length()); j++) { |
| 1034 |
if ((n & (1 << j)) == 0) { |
| 1035 |
table_builder.Add(kFail, {}, 0); |
| 1036 |
goto next; |
| 1037 |
} |
| 1038 |
} |
| 1039 |
table_builder.Add(kEmitOk, {static_cast<uint8_t>(sym.symbol)}, 0); |
| 1040 |
goto next; |
| 1041 |
} |
| 1042 |
} |
| 1043 |
table_builder.Add(kFail, {}, 0); |
| 1044 |
next:; |
| 1045 |
} |
| 1046 |
table_builder.Build(); |
| 1047 |
c->Add(absl::StrCat("const auto index = buffer_ & ", (1 << i) - 1, ";")); |
| 1048 |
c->Add(absl::StrCat("const auto op = ", table_builder.OpAccessor("index"), |
| 1049 |
";")); |
| 1050 |
if (table_builder.ConsumeBits() != 0) { |
| 1051 |
fprintf(stderr, "consume bits = %d\n", table_builder.ConsumeBits()); |
| 1052 |
abort(); |
| 1053 |
} |
| 1054 |
auto s_fin = c->Add<Switch>( |
| 1055 |
absl::StrCat("op & ", (1 << table_builder.MatchBits()) - 1)); |
| 1056 |
auto emit_ok = s_fin->Case(absl::StrCat(kEmitOk)); |
| 1057 |
emit_ok->Add(absl::StrCat( |
| 1058 |
"sink_(", |
| 1059 |
table_builder.EmitAccessor( |
| 1060 |
"index", absl::StrCat("op >>", table_builder.MatchBits())), |
| 1061 |
");")); |
| 1062 |
emit_ok->Add("break;"); |
| 1063 |
auto fail = s_fin->Case(absl::StrCat(kFail)); |
| 1064 |
fail->Add("ok_ = false;"); |
| 1065 |
fail->Add("break;"); |
| 1066 |
c->Add("return;"); |
| 1067 |
} |
| 1068 |
} |
| 1069 |
|
| 1070 |
void BuildCtx::AddStep(SymSet start_syms, int num_bits, bool is_top, |
| 1071 |
bool refill, int depth, Sink* out) { |
| 1072 |
TableBuilder table_builder(this); |
| 1073 |
if (refill) { |
| 1074 |
out->Add(absl::StrCat("if (!", fun_maker_->RefillTo(num_bits), ") {")); |
| 1075 |
auto ifblk = out->Add<Indent>(); |
| 1076 |
if (!is_top) { |
| 1077 |
Sym some = start_syms[0]; |
| 1078 |
auto sym = grpc_chttp2_huffsyms[some.symbol]; |
| 1079 |
int consumed_len = (sym.length - some.bits.length()); |
| 1080 |
uint32_t consumed_mask = sym.bits >> some.bits.length(); |
| 1081 |
bool all_ones_so_far = consumed_mask == ((1 << consumed_len) - 1); |
| 1082 |
AddDone(start_syms, num_bits, all_ones_so_far, |
| 1083 |
fun_maker_->CallNewFun("Done", ifblk)); |
| 1084 |
ifblk->Add("return;"); |
| 1085 |
} else { |
| 1086 |
AddDone(start_syms, num_bits, true, |
| 1087 |
fun_maker_->CallNewFun("Done", ifblk)); |
| 1088 |
ifblk->Add("break;"); |
| 1089 |
} |
| 1090 |
out->Add("}"); |
| 1091 |
} |
| 1092 |
out->Add(absl::StrCat("const auto index = (buffer_ >> (buffer_len_ - ", |
| 1093 |
num_bits, ")) & 0x", absl::Hex((1 << num_bits) - 1), |
| 1094 |
";")); |
| 1095 |
std::map<MatchCase, int> match_cases; |
| 1096 |
for (int i = 0; i < (1 << num_bits); i++) { |
| 1097 |
auto actions = ActionsFor(BitQueue(i, num_bits), start_syms, is_top); |
| 1098 |
auto add_case = [&match_cases](MatchCase match_case) { |
| 1099 |
if (match_cases.find(match_case) == match_cases.end()) { |
| 1100 |
match_cases[match_case] = match_cases.size(); |
| 1101 |
} |
| 1102 |
return match_cases[match_case]; |
| 1103 |
}; |
| 1104 |
if (actions.emit.size() == 1 && actions.emit[0] == 256) { |
| 1105 |
table_builder.Add(add_case(End{}), {}, actions.consumed); |
| 1106 |
} else if (actions.consumed == 0) { |
| 1107 |
table_builder.Add(add_case(Unmatched{std::move(actions.remaining)}), {}, |
| 1108 |
num_bits); |
| 1109 |
} else { |
| 1110 |
std::vector<uint8_t> emit; |
| 1111 |
for (auto sym : actions.emit) emit.push_back(sym); |
| 1112 |
table_builder.Add( |
| 1113 |
add_case(Matched{static_cast<int>(actions.emit.size())}), |
| 1114 |
std::move(emit), actions.consumed); |
| 1115 |
} |
| 1116 |
} |
| 1117 |
table_builder.Build(); |
| 1118 |
out->Add( |
| 1119 |
absl::StrCat("const auto op = ", table_builder.OpAccessor("index"), ";")); |
| 1120 |
out->Add(absl::StrCat("const int consumed = op & ", |
| 1121 |
(1 << table_builder.ConsumeBits()) - 1, ";")); |
| 1122 |
out->Add("buffer_len_ -= consumed;"); |
| 1123 |
out->Add(absl::StrCat("const auto emit_ofs = op >> ", |
| 1124 |
table_builder.ConsumeBits() + table_builder.MatchBits(), |
| 1125 |
";")); |
| 1126 |
if (match_cases.size() == 1) { |
| 1127 |
AddMatchBody(&table_builder, "index", "emit_ofs", |
| 1128 |
match_cases.begin()->first, is_top, refill, depth, out); |
| 1129 |
} else { |
| 1130 |
auto s = out->Add<Switch>( |
| 1131 |
absl::StrCat("(op >> ", table_builder.ConsumeBits(), ") & ", |
| 1132 |
(1 << table_builder.MatchBits()) - 1)); |
| 1133 |
for (auto kv : match_cases) { |
| 1134 |
auto c = s->Case(absl::StrCat(kv.second)); |
| 1135 |
AddMatchBody(&table_builder, "index", "emit_ofs", kv.first, is_top, |
| 1136 |
refill, depth, c); |
| 1137 |
c->Add("break;"); |
| 1138 |
} |
| 1139 |
} |
| 1140 |
} |
| 1141 |
|
| 1142 |
void BuildCtx::AddMatchBody(TableBuilder* table_builder, std::string index, |
| 1143 |
std::string ofs, const MatchCase& match_case, |
| 1144 |
bool is_top, bool refill, int depth, Sink* out) { |
| 1145 |
if (absl::holds_alternative<End>(match_case)) { |
| 1146 |
out->Add("begin_ = end_;"); |
| 1147 |
out->Add("buffer_len_ = 0;"); |
| 1148 |
return; |
| 1149 |
} |
| 1150 |
if (auto* p = absl::get_if<Unmatched>(&match_case)) { |
| 1151 |
if (refill) { |
| 1152 |
int max_bits = 0; |
| 1153 |
for (auto sym : p->syms) max_bits = std::max(max_bits, sym.bits.length()); |
| 1154 |
AddStep(p->syms, |
| 1155 |
depth + 1 >= max_bits_for_depth_.size() |
| 1156 |
? max_bits |
| 1157 |
: std::min(max_bits, max_bits_for_depth_[depth + 1]), |
| 1158 |
false, true, depth + 1, |
| 1159 |
fun_maker_->CallNewFun("DecodeStep", out)); |
| 1160 |
} |
| 1161 |
return; |
| 1162 |
} |
| 1163 |
const auto& matched = absl::get<Matched>(match_case); |
| 1164 |
for (int i = 0; i < matched.emits; i++) { |
| 1165 |
out->Add(absl::StrCat( |
| 1166 |
"sink_(", |
| 1167 |
table_builder->EmitAccessor(index, absl::StrCat(ofs, " + ", i)), ");")); |
| 1168 |
} |
| 1169 |
} |
| 1170 |
|
| 1171 |
/////////////////////////////////////////////////////////////////////////////// |
| 1172 |
// Driver code |
| 1173 |
|
| 1174 |
// Generated header and source code |
| 1175 |
struct BuildOutput { |
| 1176 |
std::string header; |
| 1177 |
std::string source; |
| 1178 |
}; |
| 1179 |
|
| 1180 |
// Given max_bits_for_depth = {n1,n2,n3,...} |
| 1181 |
// Build a decoder that first considers n1 bits, then n2, then n3, ... |
| 1182 |
BuildOutput Build(std::vector<int> max_bits_for_depth) { |
| 1183 |
auto hdr = std::make_unique<Sink>(); |
| 1184 |
auto src = std::make_unique<Sink>(); |
| 1185 |
hdr->Add<Prelude>(); |
| 1186 |
src->Add<Prelude>(); |
| 1187 |
hdr->Add("#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_DECODE_HUFF_H"); |
| 1188 |
hdr->Add("#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_DECODE_HUFF_H"); |
| 1189 |
src->Add( |
| 1190 |
"#include \"src/core/ext/transport/chttp2/transport/decode_huff.h\""); |
| 1191 |
hdr->Add("#include <cstddef>"); |
| 1192 |
hdr->Add("#include <grpc/support/port_platform.h>"); |
| 1193 |
src->Add("#include <grpc/support/port_platform.h>"); |
| 1194 |
hdr->Add("#include <cstdint>"); |
| 1195 |
hdr->Add( |
| 1196 |
absl::StrCat("// GEOMETRY: ", absl::StrJoin(max_bits_for_depth, ","))); |
| 1197 |
hdr->Add("namespace grpc_core {"); |
| 1198 |
src->Add("namespace grpc_core {"); |
| 1199 |
hdr->Add("class HuffDecoderCommon {"); |
| 1200 |
hdr->Add(" protected:"); |
| 1201 |
auto global_fns = hdr->Add<Indent>(); |
| 1202 |
hdr->Add(" private:"); |
| 1203 |
auto global_decls = hdr->Add<Indent>(); |
| 1204 |
hdr->Add("};"); |
| 1205 |
hdr->Add( |
| 1206 |
"template<typename F> class HuffDecoder : public HuffDecoderCommon {"); |
| 1207 |
hdr->Add(" public:"); |
| 1208 |
auto pub = hdr->Add<Indent>(); |
| 1209 |
hdr->Add(" private:"); |
| 1210 |
auto prv = hdr->Add<Indent>(); |
| 1211 |
FunMaker fun_maker(prv->Add<Sink>()); |
| 1212 |
hdr->Add("};"); |
| 1213 |
hdr->Add("} // namespace grpc_core"); |
| 1214 |
hdr->Add("#endif // GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_DECODE_HUFF_H"); |
| 1215 |
auto global_values = src->Add<Indent>(); |
| 1216 |
src->Add("} // namespace grpc_core"); |
| 1217 |
BuildCtx ctx(std::move(max_bits_for_depth), global_fns, global_decls, |
| 1218 |
global_values, &fun_maker); |
| 1219 |
// constructor |
| 1220 |
pub->Add( |
| 1221 |
"HuffDecoder(F sink, const uint8_t* begin, const uint8_t* end) : " |
| 1222 |
"sink_(sink), begin_(begin), end_(end) {}"); |
| 1223 |
// members |
| 1224 |
prv->Add("F sink_;"); |
| 1225 |
prv->Add("const uint8_t* begin_;"); |
| 1226 |
prv->Add("const uint8_t* const end_;"); |
| 1227 |
prv->Add("uint64_t buffer_ = 0;"); |
| 1228 |
prv->Add("int buffer_len_ = 0;"); |
| 1229 |
prv->Add("bool ok_ = true;"); |
| 1230 |
prv->Add("bool done_ = false;"); |
| 1231 |
// main fn |
| 1232 |
pub->Add("bool Run() {"); |
| 1233 |
auto body = pub->Add<Indent>(); |
| 1234 |
body->Add("while (!done_) {"); |
| 1235 |
ctx.AddStep(AllSyms(), ctx.MaxBitsForTop(), true, true, 0, |
| 1236 |
body->Add<Indent>()); |
| 1237 |
body->Add("}"); |
| 1238 |
body->Add("return ok_;"); |
| 1239 |
pub->Add("}"); |
| 1240 |
return {hdr->ToString(), src->ToString()}; |
| 1241 |
} |
| 1242 |
|
| 1243 |
// Generate all permutations of max_bits_for_depth for the Build function, |
| 1244 |
// with a minimum step size of 5 bits (needed for http2 I think) and a |
| 1245 |
// configurable maximum step size. |
| 1246 |
class PermutationBuilder { |
| 1247 |
public: |
| 1248 |
explicit PermutationBuilder(int max_depth) : max_depth_(max_depth) {} |
| 1249 |
std::vector<std::vector<int>> Run() { |
| 1250 |
Step({}); |
| 1251 |
return std::move(perms_); |
| 1252 |
} |
| 1253 |
|
| 1254 |
private: |
| 1255 |
void Step(std::vector<int> so_far) { |
| 1256 |
int sum_so_far = std::accumulate(so_far.begin(), so_far.end(), 0); |
| 1257 |
if (so_far.size() > max_depth_ || |
| 1258 |
(so_far.size() == max_depth_ && sum_so_far != 30)) { |
| 1259 |
return; |
| 1260 |
} |
| 1261 |
if (sum_so_far + 5 > 30) { |
| 1262 |
perms_.emplace_back(std::move(so_far)); |
| 1263 |
return; |
| 1264 |
} |
| 1265 |
for (int i = 5; i <= std::min(30 - sum_so_far, 16); i++) { |
| 1266 |
auto p = so_far; |
| 1267 |
p.push_back(i); |
| 1268 |
Step(std::move(p)); |
| 1269 |
} |
| 1270 |
} |
| 1271 |
|
| 1272 |
const int max_depth_; |
| 1273 |
std::vector<std::vector<int>> perms_; |
| 1274 |
}; |
| 1275 |
|
| 1276 |
// Does what it says. |
| 1277 |
void WriteFile(std::string filename, std::string content) { |
| 1278 |
std::ofstream ofs(filename); |
| 1279 |
ofs << content; |
| 1280 |
} |
| 1281 |
|
| 1282 |
int main(void) { |
| 1283 |
BuildOutput best; |
| 1284 |
size_t best_len = std::numeric_limits<size_t>::max(); |
| 1285 |
std::vector<std::unique_ptr<BuildOutput>> results; |
| 1286 |
std::queue<std::thread> threads; |
| 1287 |
// Generate all permutations of max_bits_for_depth for the Build function. |
| 1288 |
// Then generate all variations of the code. |
| 1289 |
for (const auto& perm : PermutationBuilder(30).Run()) { |
| 1290 |
while (threads.size() > 200) { |
| 1291 |
threads.front().join(); |
| 1292 |
threads.pop(); |
| 1293 |
} |
| 1294 |
results.emplace_back(std::make_unique<BuildOutput>()); |
| 1295 |
threads.emplace([perm, r = results.back().get()] { *r = Build(perm); }); |
| 1296 |
} |
| 1297 |
while (!threads.empty()) { |
| 1298 |
threads.front().join(); |
| 1299 |
threads.pop(); |
| 1300 |
} |
| 1301 |
// Choose the variation that generates the least code, weighted towards header |
| 1302 |
// length |
| 1303 |
for (auto& r : results) { |
| 1304 |
size_t l = 5 * r->header.length() + r->source.length(); |
| 1305 |
if (l < best_len) { |
| 1306 |
best_len = l; |
| 1307 |
best = std::move(*r); |
| 1308 |
} |
| 1309 |
} |
| 1310 |
WriteFile("src/core/ext/transport/chttp2/transport/decode_huff.h", |
| 1311 |
best.header); |
| 1312 |
WriteFile("src/core/ext/transport/chttp2/transport/decode_huff.cc", |
| 1313 |
best.source); |
| 1314 |
return 0; |
| 1315 |
} |