CIRCT 22.0.0git
Loading...
Searching...
No Matches
TruthTable.h
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header file defines truth table utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef CIRCT_SUPPORT_TRUTHTABLE_H
14#define CIRCT_SUPPORT_TRUTHTABLE_H
15
16#include "circt/Support/LLVM.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/raw_ostream.h"
21
22namespace circt {
23
24/// Represents a boolean function as a truth table.
25///
26/// A truth table stores the output values for all possible input combinations
27/// of a boolean function. For a function with n inputs and m outputs, the
28/// truth table contains 2^n entries, each with m output bits.
29///
30/// Example: For a 2-input AND gate:
31/// - Input 00 -> Output 0
32/// - Input 01 -> Output 0
33/// - Input 10 -> Output 0
34/// - Input 11 -> Output 1
35/// This would be stored as the bit pattern 0001 in the truth table.
36///
37/// TODO: Rename this to MultiOutputTruthTable since for single-output functions
38/// we can just use llvm::APInt directly.
40 unsigned numInputs; ///< Number of inputs for this boolean function
41 unsigned numOutputs; ///< Number of outputs for this boolean function
42 llvm::APInt table; ///< Truth table data as a packed bit vector
43
44 /// Default constructor creates an empty truth table.
46
47 /// Constructor for a truth table with given dimensions and evaluation data.
49 const llvm::APInt &table)
51 assert(table.getBitWidth() == (1u << numInputs) * numOutputs &&
52 "Truth table size mismatch");
53 }
54
55 /// Constructor for a truth table with given dimensions, initialized to zero.
59
60 /// Get the output value for a given input combination.
61 llvm::APInt getOutput(const llvm::APInt &input) const;
62
63 /// Set the output value for a given input combination.
64 void setOutput(const llvm::APInt &input, const llvm::APInt &output);
65
66 /// Apply input permutation to create a new truth table.
67 /// This reorders the input variables according to the given permutation.
68 BinaryTruthTable applyPermutation(ArrayRef<unsigned> permutation) const;
69
70 /// Apply input negation to create a new truth table.
71 /// This negates selected input variables based on the mask.
72 BinaryTruthTable applyInputNegation(unsigned mask) const;
73
74 /// Apply output negation to create a new truth table.
75 /// This negates selected output variables based on the mask.
76 BinaryTruthTable applyOutputNegation(unsigned negation) const;
77
78 /// Check if this truth table is lexicographically smaller than another.
79 /// Used for canonical ordering of truth tables.
80 bool isLexicographicallySmaller(const BinaryTruthTable &other) const;
81
82 /// Equality comparison for truth tables.
83 bool operator==(const BinaryTruthTable &other) const;
84
85 /// Debug dump method for truth tables.
86 void dump(llvm::raw_ostream &os = llvm::errs()) const;
87};
88
89/// Represents the canonical form of a boolean function under NPN equivalence.
90///
91/// NPN (Negation-Permutation-Negation) equivalence considers two boolean
92/// functions equivalent if one can be obtained from the other by:
93/// 1. Negating some inputs (pre-negation)
94/// 2. Permuting the inputs
95/// 3. Negating some outputs (post-negation)
96///
97/// Example: The function ab+c is NPN equivalent to !a + b(!c) since we can
98/// transform the first function into the second by negating inputs 'a' and 'c',
99/// then reordering the inputs appropriately.
100///
101/// This canonical form is used to efficiently match cuts against library
102/// patterns, as functions in the same NPN class can be implemented by the
103/// same circuit with appropriate input/output inversions.
104struct NPNClass {
105 BinaryTruthTable truthTable; ///< Canonical truth table
106 llvm::SmallVector<unsigned> inputPermutation; ///< Input permutation applied
107 unsigned inputNegation = 0; ///< Input negation mask
108 unsigned outputNegation = 0; ///< Output negation mask
109
110 /// Default constructor creates an empty NPN class.
111 NPNClass() = default;
112
113 /// Constructor from a truth table.
115
116 NPNClass(const BinaryTruthTable &tt, llvm::SmallVector<unsigned> inputPerm,
117 unsigned inputNeg, unsigned outputNeg)
118 : truthTable(tt), inputPermutation(std::move(inputPerm)),
119 inputNegation(inputNeg), outputNegation(outputNeg) {}
120
121 /// Compute the canonical NPN form for a given truth table.
122 ///
123 /// This method exhaustively tries all possible input permutations and
124 /// negations to find the lexicographically smallest canonical form.
125 ///
126 /// FIXME: Currently we are using exact canonicalization which doesn't scale
127 /// well. For larger truth tables, semi-canonical forms should be used
128 /// instead.
130
131 /// Get input permutation from this NPN class to another equivalent NPN class.
132 ///
133 /// When two NPN classes are equivalent, they may have different input
134 /// permutations. This function computes a permutation that allows
135 /// transforming input indices from the target NPN class to input indices of
136 /// this NPN class.
137 ///
138 /// Returns a permutation vector where result[i] gives the input index in this
139 /// NPN class that corresponds to input i in the target NPN class.
140 ///
141 /// Example: If this has permutation [2,0,1] and target has [1,2,0],
142 /// the mapping allows connecting target inputs to this inputs correctly.
143 void getInputPermutation(const NPNClass &targetNPN,
144 llvm::SmallVectorImpl<unsigned> &permutation) const;
145
146 /// Equality comparison for NPN classes.
147 bool equivalentOtherThanPermutation(const NPNClass &other) const {
148 return truthTable == other.truthTable &&
149 inputNegation == other.inputNegation &&
151 }
152
153 bool isLexicographicallySmaller(const NPNClass &other) const {
154 if (truthTable.table != other.truthTable.table)
156 if (inputNegation != other.inputNegation)
157 return inputNegation < other.inputNegation;
158 return outputNegation < other.outputNegation;
159 }
160
161 /// Debug dump method for NPN classes.
162 void dump(llvm::raw_ostream &os = llvm::errs()) const;
163};
164
165//===----------------------------------------------------------------------===//
166// Truth Table Utilities
167//===----------------------------------------------------------------------===//
168
169/// Create a mask for a variable in the truth table.
170///
171/// This function generates a bitmask that identifies which minterms have a
172/// particular value for a given variable in a truth table representation.
173///
174/// For positive=true: mask has 1s where var=1 in the truth table encoding
175/// For positive=false: mask has 1s where var=0 in the truth table encoding
176///
177/// For example, with 3 variables (a,b,c) where c is LSB:
178/// - createVarMask(3, 0, true) creates mask for c=1: 0b10101010
179/// - createVarMask(3, 1, true) creates mask for b=1: 0b11001100
180/// - createVarMask(3, 2, true) creates mask for a=1: 0b11110000
181///
182/// Parameters:
183/// numVars: Number of variables in the truth table
184/// var: Variable index (0 = LSB)
185/// positive: true for var=1 mask, false for var=0 mask
186///
187/// Returns: APInt mask with numBits = 2^numVars
188llvm::APInt createVarMask(unsigned numVars, unsigned varIndex, bool positive);
189
190/// Compute cofactor of a Boolean function for a given variable.
191///
192/// A cofactor of a function f with respect to variable x is the function
193/// obtained by fixing x to a constant value:
194/// - Negative cofactor f|x=0 : f with variable x set to 0
195/// - Positive cofactor f|x=1 : f with variable x set to 1
196///
197/// Cofactors are fundamental in Boolean function decomposition and the
198/// Shannon expansion: f = x'*f|x=0 + x*f|x=1
199///
200/// In truth table representation, cofactors are computed by selecting the
201/// subset of minterms where the variable has the specified value, then
202/// replicating that pattern across the full truth table width.
203///
204/// This function returns a pair of cofactors (negative, positive) for the
205/// specified variable index.
206std::pair<llvm::APInt, llvm::APInt>
207computeCofactors(const llvm::APInt &f, unsigned numVars, unsigned varIndex);
208
209//===----------------------------------------------------------------------===//
210// ISOP (Irredundant Sum-of-Products) Utilities
211//===----------------------------------------------------------------------===//
212
213/// Represents a product term (cube) in a sum-of-products expression.
214/// Each cube is a conjunction of literals (variables or their negations).
215/// Assumes number of variables is less than 64.
216struct Cube {
217 /// Bitmask indicating which variables appear in this cube
218 uint64_t mask = 0;
219 /// Bitmask indicating which variables are negated
220 uint64_t inverted = 0;
221
222 Cube() = default;
223
224 /// Get number of literals in this cube
225 unsigned size() const { return llvm::popcount(mask); }
226
227 /// Has literal for variable at index varIndex
228 inline bool hasLiteral(unsigned varIndex) const {
229 return mask & (1ULL << varIndex);
230 }
231
232 inline void setLiteral(unsigned varIndex, bool isInverted) {
233 uint64_t varMask = 1ULL << varIndex;
234 mask |= varMask;
235 if (isInverted)
236 inverted |= varMask;
237 }
238 inline void removeLiteral(unsigned varIndex) {
239 uint64_t varMask = 1ULL << varIndex;
240 mask &= ~varMask;
241 inverted &= ~varMask;
242 }
243
244 inline bool isLiteralInverted(unsigned varIndex) const {
245 return inverted & (1ULL << varIndex);
246 }
247};
248
249/// Represents a sum-of-products expression.
250struct SOPForm {
251 llvm::SmallVector<Cube> cubes;
252 unsigned numVars;
253
255
256 /// Compute the truth table represented by this SOP form
257 llvm::APInt computeTruthTable() const;
258
259#ifndef NDEBUG
260 /// Debug dump method for SOP forms
261 void dump(llvm::raw_ostream &os = llvm::errs()) const;
262#endif
263};
264
265/// Extract ISOP (Irredundant Sum-of-Products) from a truth table.
266///
267/// Computes an ISOP cover for a Boolean function using the Minato-Morreale
268/// algorithm. An ISOP is a sum-of-products where:
269/// 1. No cube can be removed without changing the function
270/// 2. The cubes are pairwise disjoint (no minterm is covered by multiple
271/// cubes)
272///
273/// Parameters:
274/// truthTable: Single-output truth table represented as APInt
275/// numVars: Number of variables (truthTable must have 2^numVars bits)
276///
277/// Returns: SOPForm representing the ISOP cover
278SOPForm extractISOP(const llvm::APInt &truthTable, unsigned numVars);
279
280} // namespace circt
281
282#endif // CIRCT_SUPPORT_TRUTHTABLE_H
assert(baseType &&"element must be base type")
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
SOPForm extractISOP(const llvm::APInt &truthTable, unsigned numVars)
Extract ISOP (Irredundant Sum-of-Products) from a truth table.
std::pair< llvm::APInt, llvm::APInt > computeCofactors(const llvm::APInt &f, unsigned numVars, unsigned varIndex)
Compute cofactor of a Boolean function for a given variable.
llvm::APInt createVarMask(unsigned numVars, unsigned varIndex, bool positive)
Create a mask for a variable in the truth table.
Represents a boolean function as a truth table.
Definition TruthTable.h:39
BinaryTruthTable()
Default constructor creates an empty truth table.
Definition TruthTable.h:45
BinaryTruthTable(unsigned numInputs, unsigned numOutputs)
Constructor for a truth table with given dimensions, initialized to zero.
Definition TruthTable.h:56
BinaryTruthTable applyOutputNegation(unsigned negation) const
Apply output negation to create a new truth table.
llvm::APInt table
Truth table data as a packed bit vector.
Definition TruthTable.h:42
BinaryTruthTable applyInputNegation(unsigned mask) const
Apply input negation to create a new truth table.
unsigned numInputs
Number of inputs for this boolean function.
Definition TruthTable.h:40
BinaryTruthTable(unsigned numInputs, unsigned numOutputs, const llvm::APInt &table)
Constructor for a truth table with given dimensions and evaluation data.
Definition TruthTable.h:48
void dump(llvm::raw_ostream &os=llvm::errs()) const
Debug dump method for truth tables.
bool isLexicographicallySmaller(const BinaryTruthTable &other) const
Check if this truth table is lexicographically smaller than another.
bool operator==(const BinaryTruthTable &other) const
Equality comparison for truth tables.
llvm::APInt getOutput(const llvm::APInt &input) const
Get the output value for a given input combination.
BinaryTruthTable applyPermutation(ArrayRef< unsigned > permutation) const
Apply input permutation to create a new truth table.
void setOutput(const llvm::APInt &input, const llvm::APInt &output)
Set the output value for a given input combination.
unsigned numOutputs
Number of outputs for this boolean function.
Definition TruthTable.h:41
Represents a product term (cube) in a sum-of-products expression.
Definition TruthTable.h:216
Cube()=default
bool hasLiteral(unsigned varIndex) const
Has literal for variable at index varIndex.
Definition TruthTable.h:228
unsigned size() const
Get number of literals in this cube.
Definition TruthTable.h:225
void removeLiteral(unsigned varIndex)
Definition TruthTable.h:238
uint64_t inverted
Bitmask indicating which variables are negated.
Definition TruthTable.h:220
bool isLiteralInverted(unsigned varIndex) const
Definition TruthTable.h:244
void setLiteral(unsigned varIndex, bool isInverted)
Definition TruthTable.h:232
uint64_t mask
Bitmask indicating which variables appear in this cube.
Definition TruthTable.h:218
Represents the canonical form of a boolean function under NPN equivalence.
Definition TruthTable.h:104
NPNClass(const BinaryTruthTable &tt)
Constructor from a truth table.
Definition TruthTable.h:114
unsigned outputNegation
Output negation mask.
Definition TruthTable.h:108
static NPNClass computeNPNCanonicalForm(const BinaryTruthTable &tt)
Compute the canonical NPN form for a given truth table.
void getInputPermutation(const NPNClass &targetNPN, llvm::SmallVectorImpl< unsigned > &permutation) const
Get input permutation from this NPN class to another equivalent NPN class.
BinaryTruthTable truthTable
Canonical truth table.
Definition TruthTable.h:105
void dump(llvm::raw_ostream &os=llvm::errs()) const
Debug dump method for NPN classes.
NPNClass()=default
Default constructor creates an empty NPN class.
bool equivalentOtherThanPermutation(const NPNClass &other) const
Equality comparison for NPN classes.
Definition TruthTable.h:147
llvm::SmallVector< unsigned > inputPermutation
Input permutation applied.
Definition TruthTable.h:106
unsigned inputNegation
Input negation mask.
Definition TruthTable.h:107
bool isLexicographicallySmaller(const NPNClass &other) const
Definition TruthTable.h:153
NPNClass(const BinaryTruthTable &tt, llvm::SmallVector< unsigned > inputPerm, unsigned inputNeg, unsigned outputNeg)
Definition TruthTable.h:116
Represents a sum-of-products expression.
Definition TruthTable.h:250
unsigned numVars
Definition TruthTable.h:252
void dump(llvm::raw_ostream &os=llvm::errs()) const
Debug dump method for SOP forms.
llvm::SmallVector< Cube > cubes
Definition TruthTable.h:251
llvm::APInt computeTruthTable() const
Compute the truth table represented by this SOP form.
SOPForm(unsigned numVars)
Definition TruthTable.h:254