1 //===- CodeGenMapTable.cpp - Instruction Mapping Table Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // CodeGenMapTable provides functionality for the TabelGen to create
10 // relation mapping between instructions. Relation models are defined using
11 // InstrMapping as a base class. This file implements the functionality which
12 // parses these definitions and generates relation maps using the information
13 // specified there. These maps are emitted as tables in the XXXGenInstrInfo.inc
14 // file along with the functions to query them.
16 // A relationship model to relate non-predicate instructions with their
17 // predicated true/false forms can be defined as follows:
19 // def getPredOpcode : InstrMapping {
20 // let FilterClass = "PredRel";
21 // let RowFields = ["BaseOpcode"];
22 // let ColFields = ["PredSense"];
23 // let KeyCol = ["none"];
24 // let ValueCols = [["true"], ["false"]]; }
26 // CodeGenMapTable parses this map and generates a table in XXXGenInstrInfo.inc
27 // file that contains the instructions modeling this relationship. This table
28 // is defined in the function
29 // "int getPredOpcode(uint16_t Opcode, enum PredSense inPredSense)"
30 // that can be used to retrieve the predicated form of the instruction by
31 // passing its opcode value and the predicate sense (true/false) of the desired
32 // instruction as arguments.
34 // Short description of the algorithm:
36 // 1) Iterate through all the records that derive from "InstrMapping" class.
37 // 2) For each record, filter out instructions based on the FilterClass value.
38 // 3) Iterate through this set of instructions and insert them into
39 // RowInstrMap map based on their RowFields values. RowInstrMap is keyed by the
40 // vector of RowFields values and contains vectors of Records (instructions) as
41 // values. RowFields is a list of fields that are required to have the same
42 // values for all the instructions appearing in the same row of the relation
43 // table. All the instructions in a given row of the relation table have some
44 // sort of relationship with the key instruction defined by the corresponding
45 // relationship model.
47 // Ex: RowInstrMap(RowVal1, RowVal2, ...) -> [Instr1, Instr2, Instr3, ... ]
48 // Here Instr1, Instr2, Instr3 have same values (RowVal1, RowVal2) for
49 // RowFields. These groups of instructions are later matched against ValueCols
50 // to determine the column they belong to, if any.
52 // While building the RowInstrMap map, collect all the key instructions in
53 // KeyInstrVec. These are the instructions having the same values as KeyCol
54 // for all the fields listed in ColFields.
58 // Relate non-predicate instructions with their predicated true/false forms.
60 // def getPredOpcode : InstrMapping {
61 // let FilterClass = "PredRel";
62 // let RowFields = ["BaseOpcode"];
63 // let ColFields = ["PredSense"];
64 // let KeyCol = ["none"];
65 // let ValueCols = [["true"], ["false"]]; }
67 // Here, only instructions that have "none" as PredSense will be selected as key
70 // 4) For each key instruction, get the group of instructions that share the
71 // same key-value as the key instruction from RowInstrMap. Iterate over the list
72 // of columns in ValueCols (it is defined as a list<list<string> >. Therefore,
73 // it can specify multi-column relationships). For each column, find the
74 // instruction from the group that matches all the values for the column.
75 // Multiple matches are not allowed.
77 //===----------------------------------------------------------------------===//
79 #include "CodeGenTarget.h"
80 #include "llvm/Support/Format.h"
82 typedef std::map<std::string, std::vector<Record*> > InstrRelMapTy;
84 typedef std::map<std::vector<Init*>, std::vector<Record*> > RowInstrMapTy;
88 //===----------------------------------------------------------------------===//
89 // This class is used to represent InstrMapping class defined in Target.td file.
93 std::string FilterClass;
97 std::vector<ListInit*> ValueCols;
100 InstrMap(Record* MapRec) {
101 Name = MapRec->getName();
103 // FilterClass - It's used to reduce the search space only to the
104 // instructions that define the kind of relationship modeled by
105 // this InstrMapping object/record.
106 const RecordVal *Filter = MapRec->getValue("FilterClass");
107 FilterClass = Filter->getValue()->getAsUnquotedString();
109 // List of fields/attributes that need to be same across all the
110 // instructions in a row of the relation table.
111 RowFields = MapRec->getValueAsListInit("RowFields");
113 // List of fields/attributes that are constant across all the instruction
114 // in a column of the relation table. Ex: ColFields = 'predSense'
115 ColFields = MapRec->getValueAsListInit("ColFields");
117 // Values for the fields/attributes listed in 'ColFields'.
118 // Ex: KeyCol = 'noPred' -- key instruction is non predicated
119 KeyCol = MapRec->getValueAsListInit("KeyCol");
121 // List of values for the fields/attributes listed in 'ColFields', one for
122 // each column in the relation table.
124 // Ex: ValueCols = [['true'],['false']] -- it results two columns in the
125 // table. First column requires all the instructions to have predSense
126 // set to 'true' and second column requires it to be 'false'.
127 ListInit *ColValList = MapRec->getValueAsListInit("ValueCols");
129 // Each instruction map must specify at least one column for it to be valid.
130 if (ColValList->getSize() == 0)
131 throw "InstrMapping record `" + MapRec->getName() + "' has empty " +
132 "`ValueCols' field!";
134 for (unsigned i = 0, e = ColValList->getSize(); i < e; i++) {
135 ListInit *ColI = dyn_cast<ListInit>(ColValList->getElement(i));
137 // Make sure that all the sub-lists in 'ValueCols' have same number of
138 // elements as the fields in 'ColFields'.
139 if (ColI->getSize() == ColFields->getSize())
140 ValueCols.push_back(ColI);
142 throw "Record `" + MapRec->getName() + "', field `" + "ValueCols" +
143 "' entries don't match with the entries in 'ColFields'!";
148 std::string getName() const {
152 std::string getFilterClass() {
156 ListInit *getRowFields() const {
160 ListInit *getColFields() const {
164 ListInit *getKeyCol() const {
168 const std::vector<ListInit*> &getValueCols() const {
172 } // End anonymous namespace.
175 //===----------------------------------------------------------------------===//
176 // class MapTableEmitter : It builds the instruction relation maps using
177 // the information provided in InstrMapping records. It outputs these
178 // relationship maps as tables into XXXGenInstrInfo.inc file along with the
179 // functions to query them.
182 class MapTableEmitter {
184 // std::string TargetName;
185 const CodeGenTarget &Target;
186 RecordKeeper &Records;
187 // InstrMapDesc - InstrMapping record to be processed.
188 InstrMap InstrMapDesc;
190 // InstrDefs - list of instructions filtered using FilterClass defined
192 std::vector<Record*> InstrDefs;
194 // RowInstrMap - maps RowFields values to the instructions. It's keyed by the
195 // values of the row fields and contains vector of records as values.
196 RowInstrMapTy RowInstrMap;
198 // KeyInstrVec - list of key instructions.
199 std::vector<Record*> KeyInstrVec;
200 DenseMap<Record*, std::vector<Record*> > MapTable;
203 MapTableEmitter(CodeGenTarget &Target, RecordKeeper &Records, Record *IMRec):
204 Target(Target), Records(Records), InstrMapDesc(IMRec) {
205 const std::string FilterClass = InstrMapDesc.getFilterClass();
206 InstrDefs = Records.getAllDerivedDefinitions(FilterClass);
209 void buildRowInstrMap();
211 // Returns true if an instruction is a key instruction, i.e., its ColFields
212 // have same values as KeyCol.
213 bool isKeyColInstr(Record* CurInstr);
215 // Find column instruction corresponding to a key instruction based on the
216 // constraints for that column.
217 Record *getInstrForColumn(Record *KeyInstr, ListInit *CurValueCol);
219 // Find column instructions for each key instruction based
220 // on ValueCols and store them into MapTable.
221 void buildMapTable();
223 void emitBinSearch(raw_ostream &OS, unsigned TableSize);
224 void emitTablesWithFunc(raw_ostream &OS);
225 unsigned emitBinSearchTable(raw_ostream &OS);
227 // Lookup functions to query binary search tables.
228 void emitMapFuncBody(raw_ostream &OS, unsigned TableSize);
231 } // End anonymous namespace.
234 //===----------------------------------------------------------------------===//
235 // Process all the instructions that model this relation (alreday present in
236 // InstrDefs) and insert them into RowInstrMap which is keyed by the values of
237 // the fields listed as RowFields. It stores vectors of records as values.
238 // All the related instructions have the same values for the RowFields thus are
239 // part of the same key-value pair.
240 //===----------------------------------------------------------------------===//
242 void MapTableEmitter::buildRowInstrMap() {
243 for (unsigned i = 0, e = InstrDefs.size(); i < e; i++) {
244 std::vector<Record*> InstrList;
245 Record *CurInstr = InstrDefs[i];
246 std::vector<Init*> KeyValue;
247 ListInit *RowFields = InstrMapDesc.getRowFields();
248 for (unsigned j = 0, endRF = RowFields->getSize(); j < endRF; j++) {
249 Init *RowFieldsJ = RowFields->getElement(j);
250 Init *CurInstrVal = CurInstr->getValue(RowFieldsJ)->getValue();
251 KeyValue.push_back(CurInstrVal);
254 // Collect key instructions into KeyInstrVec. Later, these instructions are
255 // processed to assign column position to the instructions sharing
256 // their KeyValue in RowInstrMap.
257 if (isKeyColInstr(CurInstr))
258 KeyInstrVec.push_back(CurInstr);
260 RowInstrMap[KeyValue].push_back(CurInstr);
264 //===----------------------------------------------------------------------===//
265 // Return true if an instruction is a KeyCol instruction.
266 //===----------------------------------------------------------------------===//
268 bool MapTableEmitter::isKeyColInstr(Record* CurInstr) {
269 ListInit *ColFields = InstrMapDesc.getColFields();
270 ListInit *KeyCol = InstrMapDesc.getKeyCol();
272 // Check if the instruction is a KeyCol instruction.
273 bool MatchFound = true;
274 for (unsigned j = 0, endCF = ColFields->getSize();
275 (j < endCF) && MatchFound; j++) {
276 RecordVal *ColFieldName = CurInstr->getValue(ColFields->getElement(j));
277 std::string CurInstrVal = ColFieldName->getValue()->getAsUnquotedString();
278 std::string KeyColValue = KeyCol->getElement(j)->getAsUnquotedString();
279 MatchFound = (CurInstrVal == KeyColValue);
284 //===----------------------------------------------------------------------===//
285 // Build a map to link key instructions with the column instructions arranged
286 // according to their column positions.
287 //===----------------------------------------------------------------------===//
289 void MapTableEmitter::buildMapTable() {
290 // Find column instructions for a given key based on the ColField
292 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
293 unsigned NumOfCols = ValueCols.size();
294 for (unsigned j = 0, endKI = KeyInstrVec.size(); j < endKI; j++) {
295 Record *CurKeyInstr = KeyInstrVec[j];
296 std::vector<Record*> ColInstrVec(NumOfCols);
298 // Find the column instruction based on the constraints for the column.
299 for (unsigned ColIdx = 0; ColIdx < NumOfCols; ColIdx++) {
300 ListInit *CurValueCol = ValueCols[ColIdx];
301 Record *ColInstr = getInstrForColumn(CurKeyInstr, CurValueCol);
302 ColInstrVec[ColIdx] = ColInstr;
304 MapTable[CurKeyInstr] = ColInstrVec;
308 //===----------------------------------------------------------------------===//
309 // Find column instruction based on the constraints for that column.
310 //===----------------------------------------------------------------------===//
312 Record *MapTableEmitter::getInstrForColumn(Record *KeyInstr,
313 ListInit *CurValueCol) {
314 ListInit *RowFields = InstrMapDesc.getRowFields();
315 std::vector<Init*> KeyValue;
317 // Construct KeyValue using KeyInstr's values for RowFields.
318 for (unsigned j = 0, endRF = RowFields->getSize(); j < endRF; j++) {
319 Init *RowFieldsJ = RowFields->getElement(j);
320 Init *KeyInstrVal = KeyInstr->getValue(RowFieldsJ)->getValue();
321 KeyValue.push_back(KeyInstrVal);
324 // Get all the instructions that share the same KeyValue as the KeyInstr
325 // in RowInstrMap. We search through these instructions to find a match
326 // for the current column, i.e., the instruction which has the same values
327 // as CurValueCol for all the fields in ColFields.
328 const std::vector<Record*> &RelatedInstrVec = RowInstrMap[KeyValue];
330 ListInit *ColFields = InstrMapDesc.getColFields();
331 Record *MatchInstr = NULL;
333 for (unsigned i = 0, e = RelatedInstrVec.size(); i < e; i++) {
334 bool MatchFound = true;
335 Record *CurInstr = RelatedInstrVec[i];
336 for (unsigned j = 0, endCF = ColFields->getSize();
337 (j < endCF) && MatchFound; j++) {
338 Init *ColFieldJ = ColFields->getElement(j);
339 Init *CurInstrInit = CurInstr->getValue(ColFieldJ)->getValue();
340 std::string CurInstrVal = CurInstrInit->getAsUnquotedString();
341 Init *ColFieldJVallue = CurValueCol->getElement(j);
342 MatchFound = (CurInstrVal == ColFieldJVallue->getAsUnquotedString());
346 if (MatchInstr) // Already had a match
347 // Error if multiple matches are found for a column.
348 throw "Multiple matches found for `" + KeyInstr->getName() +
349 "', for the relation `" + InstrMapDesc.getName();
351 MatchInstr = CurInstr;
357 //===----------------------------------------------------------------------===//
358 // Emit one table per relation. Only instructions with a valid relation of a
359 // given type are included in the table sorted by their enum values (opcodes).
360 // Binary search is used for locating instructions in the table.
361 //===----------------------------------------------------------------------===//
363 unsigned MapTableEmitter::emitBinSearchTable(raw_ostream &OS) {
365 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
366 Target.getInstructionsByEnumValue();
367 std::string TargetName = Target.getName();
368 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
369 unsigned NumCol = ValueCols.size();
370 unsigned TotalNumInstr = NumberedInstructions.size();
371 unsigned TableSize = 0;
373 OS << "static const uint16_t "<<InstrMapDesc.getName();
374 // Number of columns in the table are NumCol+1 because key instructions are
375 // emitted as first column.
376 OS << "Table[]["<< NumCol+1 << "] = {\n";
377 for (unsigned i = 0; i < TotalNumInstr; i++) {
378 Record *CurInstr = NumberedInstructions[i]->TheDef;
379 std::vector<Record*> ColInstrs = MapTable[CurInstr];
380 std::string OutStr("");
381 unsigned RelExists = 0;
382 if (ColInstrs.size()) {
383 for (unsigned j = 0; j < NumCol; j++) {
384 if (ColInstrs[j] != NULL) {
387 OutStr += TargetName;
389 OutStr += ColInstrs[j]->getName();
390 } else { OutStr += ", -1";}
394 OS << " { " << TargetName << "::" << CurInstr->getName();
395 OS << OutStr <<" },\n";
401 OS << " { " << TargetName << "::" << "INSTRUCTION_LIST_END, ";
402 OS << TargetName << "::" << "INSTRUCTION_LIST_END }";
404 OS << "}; // End of " << InstrMapDesc.getName() << "Table\n\n";
408 //===----------------------------------------------------------------------===//
409 // Emit binary search algorithm as part of the functions used to query
411 //===----------------------------------------------------------------------===//
413 void MapTableEmitter::emitBinSearch(raw_ostream &OS, unsigned TableSize) {
414 OS << " unsigned mid;\n";
415 OS << " unsigned start = 0;\n";
416 OS << " unsigned end = " << TableSize << ";\n";
417 OS << " while (start < end) {\n";
418 OS << " mid = start + (end - start)/2;\n";
419 OS << " if (Opcode == " << InstrMapDesc.getName() << "Table[mid][0]) {\n";
422 OS << " if (Opcode < " << InstrMapDesc.getName() << "Table[mid][0])\n";
423 OS << " end = mid;\n";
425 OS << " start = mid + 1;\n";
427 OS << " if (start == end)\n";
428 OS << " return -1; // Instruction doesn't exist in this table.\n\n";
431 //===----------------------------------------------------------------------===//
432 // Emit functions to query relation tables.
433 //===----------------------------------------------------------------------===//
435 void MapTableEmitter::emitMapFuncBody(raw_ostream &OS,
436 unsigned TableSize) {
438 ListInit *ColFields = InstrMapDesc.getColFields();
439 const std::vector<ListInit*> &ValueCols = InstrMapDesc.getValueCols();
441 // Emit binary search algorithm to locate instructions in the
442 // relation table. If found, return opcode value from the appropriate column
444 emitBinSearch(OS, TableSize);
446 if (ValueCols.size() > 1) {
447 for (unsigned i = 0, e = ValueCols.size(); i < e; i++) {
448 ListInit *ColumnI = ValueCols[i];
449 for (unsigned j = 0, ColSize = ColumnI->getSize(); j < ColSize; j++) {
450 std::string ColName = ColFields->getElement(j)->getAsUnquotedString();
451 OS << " if (in" << ColName;
453 OS << ColName << "_" << ColumnI->getElement(j)->getAsUnquotedString();
454 if (j < ColumnI->getSize() - 1) OS << " && ";
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() << "\n";
482 OS << "int "<< InstrMapDesc.getName() << "(uint16_t Opcode";
483 if (ValueCols.size() > 1) {
484 for (unsigned i = 0, e = ColFields->getSize(); i < e; i++) {
485 std::string ColName = ColFields->getElement(i)->getAsUnquotedString();
486 OS << ", enum " << ColName << " in" << ColName << ") {\n";
488 } else { OS << ") {\n"; }
491 unsigned TableSize = emitBinSearchTable(OS);
493 // Emit rest of the function body.
494 emitMapFuncBody(OS, TableSize);
497 //===----------------------------------------------------------------------===//
498 // Emit enums for the column fields across all the instruction maps.
499 //===----------------------------------------------------------------------===//
501 static void emitEnums(raw_ostream &OS, RecordKeeper &Records) {
503 std::vector<Record*> InstrMapVec;
504 InstrMapVec = Records.getAllDerivedDefinitions("InstrMapping");
505 std::map<std::string, std::vector<Init*> > ColFieldValueMap;
507 // Iterate over all InstrMapping records and create a map between column
508 // fields and their possible values across all records.
509 for (unsigned i = 0, e = InstrMapVec.size(); i < e; i++) {
510 Record *CurMap = InstrMapVec[i];
512 ColFields = CurMap->getValueAsListInit("ColFields");
513 ListInit *List = CurMap->getValueAsListInit("ValueCols");
514 std::vector<ListInit*> ValueCols;
515 unsigned ListSize = List->getSize();
517 for (unsigned j = 0; j < ListSize; j++) {
518 ListInit *ListJ = dyn_cast<ListInit>(List->getElement(j));
520 if (ListJ->getSize() != ColFields->getSize()) {
521 throw "Record `" + CurMap->getName() + "', field `" + "ValueCols" +
522 "' entries don't match with the entries in 'ColFields' !";
524 ValueCols.push_back(ListJ);
527 for (unsigned j = 0, endCF = ColFields->getSize(); j < endCF; j++) {
528 for (unsigned k = 0; k < ListSize; k++){
529 std::string ColName = ColFields->getElement(j)->getAsUnquotedString();
530 ColFieldValueMap[ColName].push_back((ValueCols[k])->getElement(j));
535 for (std::map<std::string, std::vector<Init*> >::iterator
536 II = ColFieldValueMap.begin(), IE = ColFieldValueMap.end();
538 std::vector<Init*> FieldValues = (*II).second;
539 unsigned FieldSize = FieldValues.size();
541 // Delete duplicate entries from ColFieldValueMap
542 for (unsigned i = 0; i < FieldSize - 1; i++) {
543 Init *CurVal = FieldValues[i];
544 for (unsigned j = i+1; j < FieldSize; j++) {
545 if (CurVal == FieldValues[j]) {
546 FieldValues.erase(FieldValues.begin()+j);
551 // Emit enumerated values for the column fields.
552 OS << "enum " << (*II).first << " {\n";
553 for (unsigned i = 0; i < FieldSize; i++) {
554 OS << "\t" << (*II).first << "_" << FieldValues[i]->getAsUnquotedString();
555 if (i != FieldValues.size() - 1)
564 //===----------------------------------------------------------------------===//
565 // Parse 'InstrMapping' records and use the information to form relationship
566 // between instructions. These relations are emitted as a tables along with the
567 // functions to query them.
568 //===----------------------------------------------------------------------===//
569 void EmitMapTable(RecordKeeper &Records, raw_ostream &OS) {
570 CodeGenTarget Target(Records);
571 std::string TargetName = Target.getName();
572 std::vector<Record*> InstrMapVec;
573 InstrMapVec = Records.getAllDerivedDefinitions("InstrMapping");
575 if (!InstrMapVec.size())
578 OS << "#ifdef GET_INSTRMAP_INFO\n";
579 OS << "#undef GET_INSTRMAP_INFO\n";
580 OS << "namespace llvm {\n\n";
581 OS << "namespace " << TargetName << " {\n\n";
583 // Emit coulumn field names and their values as enums.
584 emitEnums(OS, Records);
586 // Iterate over all instruction mapping records and construct relationship
587 // maps based on the information specified there.
589 for (unsigned i = 0, e = InstrMapVec.size(); i < e; i++) {
590 MapTableEmitter IMap(Target, Records, InstrMapVec[i]);
592 // Build RowInstrMap to group instructions based on their values for
593 // RowFields. In the process, also collect key instructions into
595 IMap.buildRowInstrMap();
597 // Build MapTable to map key instructions with the corresponding column
599 IMap.buildMapTable();
601 // Emit map tables and the functions to query them.
602 IMap.emitTablesWithFunc(OS);
604 OS << "} // End " << TargetName << " namespace\n";
605 OS << "} // End llvm namespace\n";
606 OS << "#endif // GET_INSTRMAP_INFO\n\n";
609 } // End llvm namespace