1 //===- CodeGenMapTable.cpp - Instruction Mapping Table Generator ----------===//
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
7 //===----------------------------------------------------------------------===//
8 // CodeGenMapTable provides functionality for the TableGen to create
9 // relation mapping between instructions. Relation models are defined using
10 // InstrMapping as a base class. This file implements the functionality which
11 // parses these definitions and generates relation maps using the information
12 // specified there. These maps are emitted as tables in the XXXGenInstrInfo.inc
13 // file along with the functions to query them.
15 // A relationship model to relate non-predicate instructions with their
16 // predicated true/false forms can be defined as follows:
18 // def getPredOpcode : InstrMapping {
19 // let FilterClass = "PredRel";
20 // let RowFields = ["BaseOpcode"];
21 // let ColFields = ["PredSense"];
22 // let KeyCol = ["none"];
23 // let ValueCols = [["true"], ["false"]]; }
25 // CodeGenMapTable parses this map and generates a table in XXXGenInstrInfo.inc
26 // file that contains the instructions modeling this relationship. This table
27 // is defined in the function
28 // "int getPredOpcode(uint16_t Opcode, enum PredSense inPredSense)"
29 // that can be used to retrieve the predicated form of the instruction by
30 // passing its opcode value and the predicate sense (true/false) of the desired
31 // instruction as arguments.
33 // Short description of the algorithm:
35 // 1) Iterate through all the records that derive from "InstrMapping" class.
36 // 2) For each record, filter out instructions based on the FilterClass value.
37 // 3) Iterate through this set of instructions and insert them into
38 // RowInstrMap map based on their RowFields values. RowInstrMap is keyed by the
39 // vector of RowFields values and contains vectors of Records (instructions) as
40 // values. RowFields is a list of fields that are required to have the same
41 // values for all the instructions appearing in the same row of the relation
42 // table. All the instructions in a given row of the relation table have some
43 // sort of relationship with the key instruction defined by the corresponding
44 // relationship model.
46 // Ex: RowInstrMap(RowVal1, RowVal2, ...) -> [Instr1, Instr2, Instr3, ... ]
47 // Here Instr1, Instr2, Instr3 have same values (RowVal1, RowVal2) for
48 // RowFields. These groups of instructions are later matched against ValueCols
49 // to determine the column they belong to, if any.
51 // While building the RowInstrMap map, collect all the key instructions in
52 // KeyInstrVec. These are the instructions having the same values as KeyCol
53 // for all the fields listed in ColFields.
57 // Relate non-predicate instructions with their predicated true/false forms.
59 // def getPredOpcode : InstrMapping {
60 // let FilterClass = "PredRel";
61 // let RowFields = ["BaseOpcode"];
62 // let ColFields = ["PredSense"];
63 // let KeyCol = ["none"];
64 // let ValueCols = [["true"], ["false"]]; }
66 // Here, only instructions that have "none" as PredSense will be selected as key
69 // 4) For each key instruction, get the group of instructions that share the
70 // same key-value as the key instruction from RowInstrMap. Iterate over the list
71 // of columns in ValueCols (it is defined as a list<list<string> >. Therefore,
72 // it can specify multi-column relationships). For each column, find the
73 // instruction from the group that matches all the values for the column.
74 // Multiple matches are not allowed.
76 //===----------------------------------------------------------------------===//
78 #include "CodeGenInstruction.h"
79 #include "CodeGenTarget.h"
80 #include "llvm/TableGen/Error.h"
81 #include "llvm/TableGen/Record.h"
83 typedef std::map
<std::string
, std::vector
<Record
*> > InstrRelMapTy
;
85 typedef std::map
<std::vector
<Init
*>, std::vector
<Record
*> > RowInstrMapTy
;
89 //===----------------------------------------------------------------------===//
90 // This class is used to represent InstrMapping class defined in Target.td file.
94 std::string FilterClass
;
98 std::vector
<ListInit
*> ValueCols
;
101 InstrMap(Record
* MapRec
) {
102 Name
= std::string(MapRec
->getName());
104 // FilterClass - It's used to reduce the search space only to the
105 // instructions that define the kind of relationship modeled by
106 // this InstrMapping object/record.
107 const RecordVal
*Filter
= MapRec
->getValue("FilterClass");
108 FilterClass
= Filter
->getValue()->getAsUnquotedString();
110 // List of fields/attributes that need to be same across all the
111 // instructions in a row of the relation table.
112 RowFields
= MapRec
->getValueAsListInit("RowFields");
114 // List of fields/attributes that are constant across all the instruction
115 // in a column of the relation table. Ex: ColFields = 'predSense'
116 ColFields
= MapRec
->getValueAsListInit("ColFields");
118 // Values for the fields/attributes listed in 'ColFields'.
119 // Ex: KeyCol = 'noPred' -- key instruction is non-predicated
120 KeyCol
= MapRec
->getValueAsListInit("KeyCol");
122 // List of values for the fields/attributes listed in 'ColFields', one for
123 // each column in the relation table.
125 // Ex: ValueCols = [['true'],['false']] -- it results two columns in the
126 // table. First column requires all the instructions to have predSense
127 // set to 'true' and second column requires it to be 'false'.
128 ListInit
*ColValList
= MapRec
->getValueAsListInit("ValueCols");
130 // Each instruction map must specify at least one column for it to be valid.
131 if (ColValList
->empty())
132 PrintFatalError(MapRec
->getLoc(), "InstrMapping record `" +
133 MapRec
->getName() + "' has empty " + "`ValueCols' field!");
135 for (Init
*I
: ColValList
->getValues()) {
136 auto *ColI
= cast
<ListInit
>(I
);
138 // Make sure that all the sub-lists in 'ValueCols' have same number of
139 // elements as the fields in 'ColFields'.
140 if (ColI
->size() != ColFields
->size())
141 PrintFatalError(MapRec
->getLoc(), "Record `" + MapRec
->getName() +
142 "', field `ValueCols' entries don't match with " +
143 " the entries in 'ColFields'!");
144 ValueCols
.push_back(ColI
);
148 const std::string
&getName() const { return Name
; }
150 const std::string
&getFilterClass() const { return FilterClass
; }
152 ListInit
*getRowFields() const { return RowFields
; }
154 ListInit
*getColFields() const { return ColFields
; }
156 ListInit
*getKeyCol() const { return KeyCol
; }
158 const std::vector
<ListInit
*> &getValueCols() const {
162 } // end anonymous namespace
165 //===----------------------------------------------------------------------===//
166 // class MapTableEmitter : It builds the instruction relation maps using
167 // the information provided in InstrMapping records. It outputs these
168 // relationship maps as tables into XXXGenInstrInfo.inc file along with the
169 // functions to query them.
172 class MapTableEmitter
{
174 // std::string TargetName;
175 const CodeGenTarget
&Target
;
176 // InstrMapDesc - InstrMapping record to be processed.
177 InstrMap InstrMapDesc
;
179 // InstrDefs - list of instructions filtered using FilterClass defined
181 std::vector
<Record
*> InstrDefs
;
183 // RowInstrMap - maps RowFields values to the instructions. It's keyed by the
184 // values of the row fields and contains vector of records as values.
185 RowInstrMapTy RowInstrMap
;
187 // KeyInstrVec - list of key instructions.
188 std::vector
<Record
*> KeyInstrVec
;
189 DenseMap
<Record
*, std::vector
<Record
*> > MapTable
;
192 MapTableEmitter(CodeGenTarget
&Target
, RecordKeeper
&Records
, Record
*IMRec
):
193 Target(Target
), InstrMapDesc(IMRec
) {
194 const std::string
&FilterClass
= InstrMapDesc
.getFilterClass();
195 InstrDefs
= Records
.getAllDerivedDefinitions(FilterClass
);
198 void buildRowInstrMap();
200 // Returns true if an instruction is a key instruction, i.e., its ColFields
201 // have same values as KeyCol.
202 bool isKeyColInstr(Record
* CurInstr
);
204 // Find column instruction corresponding to a key instruction based on the
205 // constraints for that column.
206 Record
*getInstrForColumn(Record
*KeyInstr
, ListInit
*CurValueCol
);
208 // Find column instructions for each key instruction based
209 // on ValueCols and store them into MapTable.
210 void buildMapTable();
212 void emitBinSearch(raw_ostream
&OS
, unsigned TableSize
);
213 void emitTablesWithFunc(raw_ostream
&OS
);
214 unsigned emitBinSearchTable(raw_ostream
&OS
);
216 // Lookup functions to query binary search tables.
217 void emitMapFuncBody(raw_ostream
&OS
, unsigned TableSize
);
220 } // end anonymous namespace
223 //===----------------------------------------------------------------------===//
224 // Process all the instructions that model this relation (alreday present in
225 // InstrDefs) and insert them into RowInstrMap which is keyed by the values of
226 // the fields listed as RowFields. It stores vectors of records as values.
227 // All the related instructions have the same values for the RowFields thus are
228 // part of the same key-value pair.
229 //===----------------------------------------------------------------------===//
231 void MapTableEmitter::buildRowInstrMap() {
232 for (Record
*CurInstr
: InstrDefs
) {
233 std::vector
<Init
*> KeyValue
;
234 ListInit
*RowFields
= InstrMapDesc
.getRowFields();
235 for (Init
*RowField
: RowFields
->getValues()) {
236 RecordVal
*RecVal
= CurInstr
->getValue(RowField
);
237 if (RecVal
== nullptr)
238 PrintFatalError(CurInstr
->getLoc(), "No value " +
239 RowField
->getAsString() + " found in \"" +
240 CurInstr
->getName() + "\" instruction description.");
241 Init
*CurInstrVal
= RecVal
->getValue();
242 KeyValue
.push_back(CurInstrVal
);
245 // Collect key instructions into KeyInstrVec. Later, these instructions are
246 // processed to assign column position to the instructions sharing
247 // their KeyValue in RowInstrMap.
248 if (isKeyColInstr(CurInstr
))
249 KeyInstrVec
.push_back(CurInstr
);
251 RowInstrMap
[KeyValue
].push_back(CurInstr
);
255 //===----------------------------------------------------------------------===//
256 // Return true if an instruction is a KeyCol instruction.
257 //===----------------------------------------------------------------------===//
259 bool MapTableEmitter::isKeyColInstr(Record
* CurInstr
) {
260 ListInit
*ColFields
= InstrMapDesc
.getColFields();
261 ListInit
*KeyCol
= InstrMapDesc
.getKeyCol();
263 // Check if the instruction is a KeyCol instruction.
264 bool MatchFound
= true;
265 for (unsigned j
= 0, endCF
= ColFields
->size();
266 (j
< endCF
) && MatchFound
; j
++) {
267 RecordVal
*ColFieldName
= CurInstr
->getValue(ColFields
->getElement(j
));
268 std::string CurInstrVal
= ColFieldName
->getValue()->getAsUnquotedString();
269 std::string KeyColValue
= KeyCol
->getElement(j
)->getAsUnquotedString();
270 MatchFound
= (CurInstrVal
== KeyColValue
);
275 //===----------------------------------------------------------------------===//
276 // Build a map to link key instructions with the column instructions arranged
277 // according to their column positions.
278 //===----------------------------------------------------------------------===//
280 void MapTableEmitter::buildMapTable() {
281 // Find column instructions for a given key based on the ColField
283 const std::vector
<ListInit
*> &ValueCols
= InstrMapDesc
.getValueCols();
284 unsigned NumOfCols
= ValueCols
.size();
285 for (Record
*CurKeyInstr
: KeyInstrVec
) {
286 std::vector
<Record
*> ColInstrVec(NumOfCols
);
288 // Find the column instruction based on the constraints for the column.
289 for (unsigned ColIdx
= 0; ColIdx
< NumOfCols
; ColIdx
++) {
290 ListInit
*CurValueCol
= ValueCols
[ColIdx
];
291 Record
*ColInstr
= getInstrForColumn(CurKeyInstr
, CurValueCol
);
292 ColInstrVec
[ColIdx
] = ColInstr
;
294 MapTable
[CurKeyInstr
] = ColInstrVec
;
298 //===----------------------------------------------------------------------===//
299 // Find column instruction based on the constraints for that column.
300 //===----------------------------------------------------------------------===//
302 Record
*MapTableEmitter::getInstrForColumn(Record
*KeyInstr
,
303 ListInit
*CurValueCol
) {
304 ListInit
*RowFields
= InstrMapDesc
.getRowFields();
305 std::vector
<Init
*> KeyValue
;
307 // Construct KeyValue using KeyInstr's values for RowFields.
308 for (Init
*RowField
: RowFields
->getValues()) {
309 Init
*KeyInstrVal
= KeyInstr
->getValue(RowField
)->getValue();
310 KeyValue
.push_back(KeyInstrVal
);
313 // Get all the instructions that share the same KeyValue as the KeyInstr
314 // in RowInstrMap. We search through these instructions to find a match
315 // for the current column, i.e., the instruction which has the same values
316 // as CurValueCol for all the fields in ColFields.
317 const std::vector
<Record
*> &RelatedInstrVec
= RowInstrMap
[KeyValue
];
319 ListInit
*ColFields
= InstrMapDesc
.getColFields();
320 Record
*MatchInstr
= nullptr;
322 for (llvm::Record
*CurInstr
: RelatedInstrVec
) {
323 bool MatchFound
= true;
324 for (unsigned j
= 0, endCF
= ColFields
->size();
325 (j
< endCF
) && MatchFound
; j
++) {
326 Init
*ColFieldJ
= ColFields
->getElement(j
);
327 Init
*CurInstrInit
= CurInstr
->getValue(ColFieldJ
)->getValue();
328 std::string CurInstrVal
= CurInstrInit
->getAsUnquotedString();
329 Init
*ColFieldJVallue
= CurValueCol
->getElement(j
);
330 MatchFound
= (CurInstrVal
== ColFieldJVallue
->getAsUnquotedString());
335 // Already had a match
336 // Error if multiple matches are found for a column.
337 std::string KeyValueStr
;
338 for (Init
*Value
: KeyValue
) {
339 if (!KeyValueStr
.empty())
341 KeyValueStr
+= Value
->getAsString();
344 PrintFatalError("Multiple matches found for `" + KeyInstr
->getName() +
345 "', for the relation `" + InstrMapDesc
.getName() +
346 "', row fields [" + KeyValueStr
+ "], column `" +
347 CurValueCol
->getAsString() + "'");
349 MatchInstr
= CurInstr
;
355 //===----------------------------------------------------------------------===//
356 // Emit one table per relation. Only instructions with a valid relation of a
357 // given type are included in the table sorted by their enum values (opcodes).
358 // Binary search is used for locating instructions in the table.
359 //===----------------------------------------------------------------------===//
361 unsigned MapTableEmitter::emitBinSearchTable(raw_ostream
&OS
) {
363 ArrayRef
<const CodeGenInstruction
*> NumberedInstructions
=
364 Target
.getInstructionsByEnumValue();
365 StringRef Namespace
= Target
.getInstNamespace();
366 const std::vector
<ListInit
*> &ValueCols
= InstrMapDesc
.getValueCols();
367 unsigned NumCol
= ValueCols
.size();
368 unsigned TotalNumInstr
= NumberedInstructions
.size();
369 unsigned TableSize
= 0;
371 OS
<< "static const uint16_t "<<InstrMapDesc
.getName();
372 // Number of columns in the table are NumCol+1 because key instructions are
373 // emitted as first column.
374 OS
<< "Table[]["<< NumCol
+1 << "] = {\n";
375 for (unsigned i
= 0; i
< TotalNumInstr
; i
++) {
376 Record
*CurInstr
= NumberedInstructions
[i
]->TheDef
;
377 std::vector
<Record
*> ColInstrs
= MapTable
[CurInstr
];
379 unsigned RelExists
= 0;
380 if (!ColInstrs
.empty()) {
381 for (unsigned j
= 0; j
< NumCol
; j
++) {
382 if (ColInstrs
[j
] != nullptr) {
387 OutStr
+= ColInstrs
[j
]->getName();
388 } else { OutStr
+= ", (uint16_t)-1U";}
392 OS
<< " { " << Namespace
<< "::" << CurInstr
->getName();
393 OS
<< OutStr
<<" },\n";
399 OS
<< " { " << Namespace
<< "::" << "INSTRUCTION_LIST_END, ";
400 OS
<< Namespace
<< "::" << "INSTRUCTION_LIST_END }";
402 OS
<< "}; // End of " << InstrMapDesc
.getName() << "Table\n\n";
406 //===----------------------------------------------------------------------===//
407 // Emit binary search algorithm as part of the functions used to query
409 //===----------------------------------------------------------------------===//
411 void MapTableEmitter::emitBinSearch(raw_ostream
&OS
, unsigned TableSize
) {
412 OS
<< " unsigned mid;\n";
413 OS
<< " unsigned start = 0;\n";
414 OS
<< " unsigned end = " << TableSize
<< ";\n";
415 OS
<< " while (start < end) {\n";
416 OS
<< " mid = start + (end - start) / 2;\n";
417 OS
<< " if (Opcode == " << InstrMapDesc
.getName() << "Table[mid][0]) {\n";
420 OS
<< " if (Opcode < " << InstrMapDesc
.getName() << "Table[mid][0])\n";
421 OS
<< " end = mid;\n";
423 OS
<< " start = mid + 1;\n";
425 OS
<< " if (start == end)\n";
426 OS
<< " return -1; // Instruction doesn't exist in this table.\n\n";
429 //===----------------------------------------------------------------------===//
430 // Emit functions to query relation tables.
431 //===----------------------------------------------------------------------===//
433 void MapTableEmitter::emitMapFuncBody(raw_ostream
&OS
,
434 unsigned TableSize
) {
436 ListInit
*ColFields
= InstrMapDesc
.getColFields();
437 const std::vector
<ListInit
*> &ValueCols
= InstrMapDesc
.getValueCols();
439 // Emit binary search algorithm to locate instructions in the
440 // relation table. If found, return opcode value from the appropriate column
442 emitBinSearch(OS
, TableSize
);
444 if (ValueCols
.size() > 1) {
445 for (unsigned i
= 0, e
= ValueCols
.size(); i
< e
; i
++) {
446 ListInit
*ColumnI
= ValueCols
[i
];
448 for (unsigned j
= 0, ColSize
= ColumnI
->size(); j
< ColSize
; ++j
) {
449 std::string ColName
= ColFields
->getElement(j
)->getAsUnquotedString();
450 OS
<< "in" << ColName
;
452 OS
<< ColName
<< "_" << ColumnI
->getElement(j
)->getAsUnquotedString();
453 if (j
< ColumnI
->size() - 1)
457 OS
<< " return " << InstrMapDesc
.getName();
458 OS
<< "Table[mid]["<<i
+1<<"];\n";
463 OS
<< " return " << InstrMapDesc
.getName() << "Table[mid][1];\n";
468 //===----------------------------------------------------------------------===//
469 // Emit relation tables and the functions to query them.
470 //===----------------------------------------------------------------------===//
472 void MapTableEmitter::emitTablesWithFunc(raw_ostream
&OS
) {
474 // Emit function name and the input parameters : mostly opcode value of the
475 // current instruction. However, if a table has multiple columns (more than 2
476 // since first column is used for the key instructions), then we also need
477 // to pass another input to indicate the column to be selected.
479 ListInit
*ColFields
= InstrMapDesc
.getColFields();
480 const std::vector
<ListInit
*> &ValueCols
= InstrMapDesc
.getValueCols();
481 OS
<< "// "<< InstrMapDesc
.getName() << "\nLLVM_READONLY\n";
482 OS
<< "int "<< InstrMapDesc
.getName() << "(uint16_t Opcode";
483 if (ValueCols
.size() > 1) {
484 for (Init
*CF
: ColFields
->getValues()) {
485 std::string ColName
= CF
->getAsUnquotedString();
486 OS
<< ", enum " << ColName
<< " in" << ColName
;
492 unsigned TableSize
= emitBinSearchTable(OS
);
494 // Emit rest of the function body.
495 emitMapFuncBody(OS
, TableSize
);
498 //===----------------------------------------------------------------------===//
499 // Emit enums for the column fields across all the instruction maps.
500 //===----------------------------------------------------------------------===//
502 static void emitEnums(raw_ostream
&OS
, RecordKeeper
&Records
) {
504 std::vector
<Record
*> InstrMapVec
;
505 InstrMapVec
= Records
.getAllDerivedDefinitions("InstrMapping");
506 std::map
<std::string
, std::vector
<Init
*> > ColFieldValueMap
;
508 // Iterate over all InstrMapping records and create a map between column
509 // fields and their possible values across all records.
510 for (Record
*CurMap
: InstrMapVec
) {
512 ColFields
= CurMap
->getValueAsListInit("ColFields");
513 ListInit
*List
= CurMap
->getValueAsListInit("ValueCols");
514 std::vector
<ListInit
*> ValueCols
;
515 unsigned ListSize
= List
->size();
517 for (unsigned j
= 0; j
< ListSize
; j
++) {
518 auto *ListJ
= cast
<ListInit
>(List
->getElement(j
));
520 if (ListJ
->size() != ColFields
->size())
521 PrintFatalError("Record `" + CurMap
->getName() + "', field "
522 "`ValueCols' entries don't match with the entries in 'ColFields' !");
523 ValueCols
.push_back(ListJ
);
526 for (unsigned j
= 0, endCF
= ColFields
->size(); j
< endCF
; j
++) {
527 for (unsigned k
= 0; k
< ListSize
; k
++){
528 std::string ColName
= ColFields
->getElement(j
)->getAsUnquotedString();
529 ColFieldValueMap
[ColName
].push_back((ValueCols
[k
])->getElement(j
));
534 for (auto &Entry
: ColFieldValueMap
) {
535 std::vector
<Init
*> FieldValues
= Entry
.second
;
537 // Delete duplicate entries from ColFieldValueMap
538 for (unsigned i
= 0; i
< FieldValues
.size() - 1; i
++) {
539 Init
*CurVal
= FieldValues
[i
];
540 for (unsigned j
= i
+1; j
< FieldValues
.size(); j
++) {
541 if (CurVal
== FieldValues
[j
]) {
542 FieldValues
.erase(FieldValues
.begin()+j
);
548 // Emit enumerated values for the column fields.
549 OS
<< "enum " << Entry
.first
<< " {\n";
550 for (unsigned i
= 0, endFV
= FieldValues
.size(); i
< endFV
; i
++) {
551 OS
<< "\t" << Entry
.first
<< "_" << FieldValues
[i
]->getAsUnquotedString();
561 //===----------------------------------------------------------------------===//
562 // Parse 'InstrMapping' records and use the information to form relationship
563 // between instructions. These relations are emitted as a tables along with the
564 // functions to query them.
565 //===----------------------------------------------------------------------===//
566 void EmitMapTable(RecordKeeper
&Records
, raw_ostream
&OS
) {
567 CodeGenTarget
Target(Records
);
568 StringRef NameSpace
= Target
.getInstNamespace();
569 std::vector
<Record
*> InstrMapVec
;
570 InstrMapVec
= Records
.getAllDerivedDefinitions("InstrMapping");
572 if (InstrMapVec
.empty())
575 OS
<< "#ifdef GET_INSTRMAP_INFO\n";
576 OS
<< "#undef GET_INSTRMAP_INFO\n";
577 OS
<< "namespace llvm {\n\n";
578 OS
<< "namespace " << NameSpace
<< " {\n\n";
580 // Emit coulumn field names and their values as enums.
581 emitEnums(OS
, Records
);
583 // Iterate over all instruction mapping records and construct relationship
584 // maps based on the information specified there.
586 for (Record
*CurMap
: InstrMapVec
) {
587 MapTableEmitter
IMap(Target
, Records
, CurMap
);
589 // Build RowInstrMap to group instructions based on their values for
590 // RowFields. In the process, also collect key instructions into
592 IMap
.buildRowInstrMap();
594 // Build MapTable to map key instructions with the corresponding column
596 IMap
.buildMapTable();
598 // Emit map tables and the functions to query them.
599 IMap
.emitTablesWithFunc(OS
);
601 OS
<< "} // end namespace " << NameSpace
<< "\n";
602 OS
<< "} // end namespace llvm\n";
603 OS
<< "#endif // GET_INSTRMAP_INFO\n\n";
606 } // End llvm namespace