1 //===--------------------- PredicateExpander.cpp --------------------------===//
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 /// \file
9 /// Functionalities used by the Tablegen backends to expand machine predicates.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PredicateExpander.h"
14 #include "CodeGenSchedule.h" // Definition of STIPredicateFunction.
15 
16 namespace llvm {
17 
18 void PredicateExpander::expandTrue(raw_ostream &OS) { OS << "true"; }
19 void PredicateExpander::expandFalse(raw_ostream &OS) { OS << "false"; }
20 
21 void PredicateExpander::expandCheckImmOperand(raw_ostream &OS, int OpIndex,
22                                               int ImmVal,
23                                               StringRef FunctionMapper) {
24   if (!FunctionMapper.empty())
25     OS << FunctionMapper << "(";
26   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
27      << ").getImm()";
28   if (!FunctionMapper.empty())
29     OS << ")";
30   OS << (shouldNegate() ? " != " : " == ") << ImmVal;
31 }
32 
33 void PredicateExpander::expandCheckImmOperand(raw_ostream &OS, int OpIndex,
34                                               StringRef ImmVal,
35                                               StringRef FunctionMapper) {
36   if (ImmVal.empty())
37     expandCheckImmOperandSimple(OS, OpIndex, FunctionMapper);
38 
39   if (!FunctionMapper.empty())
40     OS << FunctionMapper << "(";
41   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
42      << ").getImm()";
43   if (!FunctionMapper.empty())
44     OS << ")";
45   OS << (shouldNegate() ? " != " : " == ") << ImmVal;
46 }
47 
48 void PredicateExpander::expandCheckImmOperandSimple(raw_ostream &OS,
49                                                     int OpIndex,
50                                                     StringRef FunctionMapper) {
51   if (shouldNegate())
52     OS << "!";
53   if (!FunctionMapper.empty())
54     OS << FunctionMapper << "(";
55   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
56      << ").getImm()";
57   if (!FunctionMapper.empty())
58     OS << ")";
59 }
60 
61 void PredicateExpander::expandCheckRegOperand(raw_ostream &OS, int OpIndex,
62                                               const Record *Reg,
63                                               StringRef FunctionMapper) {
64   assert(Reg->isSubClassOf("Register") && "Expected a register Record!");
65 
66   if (!FunctionMapper.empty())
67     OS << FunctionMapper << "(";
68   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
69      << ").getReg()";
70   if (!FunctionMapper.empty())
71     OS << ")";
72   OS << (shouldNegate() ? " != " : " == ");
73   const StringRef Str = Reg->getValueAsString("Namespace");
74   if (!Str.empty())
75     OS << Str << "::";
76   OS << Reg->getName();
77 }
78 
79 
80 void PredicateExpander::expandCheckRegOperandSimple(raw_ostream &OS,
81                                                     int OpIndex,
82                                                     StringRef FunctionMapper) {
83   if (shouldNegate())
84     OS << "!";
85   if (!FunctionMapper.empty())
86     OS << FunctionMapper << "(";
87   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
88      << ").getReg()";
89   if (!FunctionMapper.empty())
90     OS << ")";
91 }
92 
93 void PredicateExpander::expandCheckInvalidRegOperand(raw_ostream &OS,
94                                                      int OpIndex) {
95   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << OpIndex
96      << ").getReg() " << (shouldNegate() ? "!= " : "== ") << "0";
97 }
98 
99 void PredicateExpander::expandCheckSameRegOperand(raw_ostream &OS, int First,
100                                                   int Second) {
101   OS << "MI" << (isByRef() ? "." : "->") << "getOperand(" << First
102      << ").getReg() " << (shouldNegate() ? "!=" : "==") << " MI"
103      << (isByRef() ? "." : "->") << "getOperand(" << Second << ").getReg()";
104 }
105 
106 void PredicateExpander::expandCheckNumOperands(raw_ostream &OS, int NumOps) {
107   OS << "MI" << (isByRef() ? "." : "->") << "getNumOperands() "
108      << (shouldNegate() ? "!= " : "== ") << NumOps;
109 }
110 
111 void PredicateExpander::expandCheckOpcode(raw_ostream &OS, const Record *Inst) {
112   OS << "MI" << (isByRef() ? "." : "->") << "getOpcode() "
113      << (shouldNegate() ? "!= " : "== ") << Inst->getValueAsString("Namespace")
114      << "::" << Inst->getName();
115 }
116 
117 void PredicateExpander::expandCheckOpcode(raw_ostream &OS,
118                                           const RecVec &Opcodes) {
119   assert(!Opcodes.empty() && "Expected at least one opcode to check!");
120   bool First = true;
121 
122   if (Opcodes.size() == 1) {
123     OS << "( ";
124     expandCheckOpcode(OS, Opcodes[0]);
125     OS << " )";
126     return;
127   }
128 
129   OS << '(';
130   increaseIndentLevel();
131   for (const Record *Rec : Opcodes) {
132     OS << '\n';
133     OS.indent(getIndentLevel() * 2);
134     if (!First)
135       OS << (shouldNegate() ? "&& " : "|| ");
136 
137     expandCheckOpcode(OS, Rec);
138     First = false;
139   }
140 
141   OS << '\n';
142   decreaseIndentLevel();
143   OS.indent(getIndentLevel() * 2);
144   OS << ')';
145 }
146 
147 void PredicateExpander::expandCheckPseudo(raw_ostream &OS,
148                                           const RecVec &Opcodes) {
149   if (shouldExpandForMC())
150     expandFalse(OS);
151   else
152     expandCheckOpcode(OS, Opcodes);
153 }
154 
155 void PredicateExpander::expandPredicateSequence(raw_ostream &OS,
156                                                 const RecVec &Sequence,
157                                                 bool IsCheckAll) {
158   assert(!Sequence.empty() && "Found an invalid empty predicate set!");
159   if (Sequence.size() == 1)
160     return expandPredicate(OS, Sequence[0]);
161 
162   // Okay, there is more than one predicate in the set.
163   bool First = true;
164   OS << (shouldNegate() ? "!(" : "(");
165   increaseIndentLevel();
166 
167   bool OldValue = shouldNegate();
168   setNegatePredicate(false);
169   for (const Record *Rec : Sequence) {
170     OS << '\n';
171     OS.indent(getIndentLevel() * 2);
172     if (!First)
173       OS << (IsCheckAll ? "&& " : "|| ");
174     expandPredicate(OS, Rec);
175     First = false;
176   }
177   OS << '\n';
178   decreaseIndentLevel();
179   OS.indent(getIndentLevel() * 2);
180   OS << ')';
181   setNegatePredicate(OldValue);
182 }
183 
184 void PredicateExpander::expandTIIFunctionCall(raw_ostream &OS,
185                                               StringRef MethodName) {
186   OS << (shouldNegate() ? "!" : "");
187   OS << TargetName << (shouldExpandForMC() ? "_MC::" : "InstrInfo::");
188   OS << MethodName << (isByRef() ? "(MI)" : "(*MI)");
189 }
190 
191 void PredicateExpander::expandCheckIsRegOperand(raw_ostream &OS, int OpIndex) {
192   OS << (shouldNegate() ? "!" : "") << "MI" << (isByRef() ? "." : "->")
193      << "getOperand(" << OpIndex << ").isReg() ";
194 }
195 
196 void PredicateExpander::expandCheckIsImmOperand(raw_ostream &OS, int OpIndex) {
197   OS << (shouldNegate() ? "!" : "") << "MI" << (isByRef() ? "." : "->")
198      << "getOperand(" << OpIndex << ").isImm() ";
199 }
200 
201 void PredicateExpander::expandCheckFunctionPredicateWithTII(
202     raw_ostream &OS, StringRef MCInstFn, StringRef MachineInstrFn,
203     StringRef TIIPtr) {
204   if (!shouldExpandForMC()) {
205     OS << (TIIPtr.empty() ? "TII" : TIIPtr) << "->" << MachineInstrFn;
206     OS << (isByRef() ? "(MI)" : "(*MI)");
207     return;
208   }
209 
210   OS << MCInstFn << (isByRef() ? "(MI" : "(*MI") << ", MCII)";
211 }
212 
213 void PredicateExpander::expandCheckFunctionPredicate(raw_ostream &OS,
214                                                      StringRef MCInstFn,
215                                                      StringRef MachineInstrFn) {
216   OS << (shouldExpandForMC() ? MCInstFn : MachineInstrFn)
217      << (isByRef() ? "(MI)" : "(*MI)");
218 }
219 
220 void PredicateExpander::expandCheckNonPortable(raw_ostream &OS,
221                                                StringRef Code) {
222   if (shouldExpandForMC())
223     return expandFalse(OS);
224 
225   OS << '(' << Code << ')';
226 }
227 
228 void PredicateExpander::expandReturnStatement(raw_ostream &OS,
229                                               const Record *Rec) {
230   std::string Buffer;
231   raw_string_ostream SS(Buffer);
232 
233   SS << "return ";
234   expandPredicate(SS, Rec);
235   SS << ";";
236   OS << Buffer;
237 }
238 
239 void PredicateExpander::expandOpcodeSwitchCase(raw_ostream &OS,
240                                                const Record *Rec) {
241   const RecVec &Opcodes = Rec->getValueAsListOfDefs("Opcodes");
242   for (const Record *Opcode : Opcodes) {
243     OS.indent(getIndentLevel() * 2);
244     OS << "case " << Opcode->getValueAsString("Namespace")
245        << "::" << Opcode->getName() << ":\n";
246   }
247 
248   increaseIndentLevel();
249   OS.indent(getIndentLevel() * 2);
250   expandStatement(OS, Rec->getValueAsDef("CaseStmt"));
251   decreaseIndentLevel();
252 }
253 
254 void PredicateExpander::expandOpcodeSwitchStatement(raw_ostream &OS,
255                                                     const RecVec &Cases,
256                                                     const Record *Default) {
257   std::string Buffer;
258   raw_string_ostream SS(Buffer);
259 
260   SS << "switch(MI" << (isByRef() ? "." : "->") << "getOpcode()) {\n";
261   for (const Record *Rec : Cases) {
262     expandOpcodeSwitchCase(SS, Rec);
263     SS << '\n';
264   }
265 
266   // Expand the default case.
267   SS.indent(getIndentLevel() * 2);
268   SS << "default:\n";
269 
270   increaseIndentLevel();
271   SS.indent(getIndentLevel() * 2);
272   expandStatement(SS, Default);
273   decreaseIndentLevel();
274   SS << '\n';
275 
276   SS.indent(getIndentLevel() * 2);
277   SS << "} // end of switch-stmt";
278   OS << Buffer;
279 }
280 
281 void PredicateExpander::expandStatement(raw_ostream &OS, const Record *Rec) {
282   // Assume that padding has been added by the caller.
283   if (Rec->isSubClassOf("MCOpcodeSwitchStatement")) {
284     expandOpcodeSwitchStatement(OS, Rec->getValueAsListOfDefs("Cases"),
285                                 Rec->getValueAsDef("DefaultCase"));
286     return;
287   }
288 
289   if (Rec->isSubClassOf("MCReturnStatement")) {
290     expandReturnStatement(OS, Rec->getValueAsDef("Pred"));
291     return;
292   }
293 
294   llvm_unreachable("No known rules to expand this MCStatement");
295 }
296 
297 void PredicateExpander::expandPredicate(raw_ostream &OS, const Record *Rec) {
298   // Assume that padding has been added by the caller.
299   if (Rec->isSubClassOf("MCTrue")) {
300     if (shouldNegate())
301       return expandFalse(OS);
302     return expandTrue(OS);
303   }
304 
305   if (Rec->isSubClassOf("MCFalse")) {
306     if (shouldNegate())
307       return expandTrue(OS);
308     return expandFalse(OS);
309   }
310 
311   if (Rec->isSubClassOf("CheckNot")) {
312     flipNegatePredicate();
313     expandPredicate(OS, Rec->getValueAsDef("Pred"));
314     flipNegatePredicate();
315     return;
316   }
317 
318   if (Rec->isSubClassOf("CheckIsRegOperand"))
319     return expandCheckIsRegOperand(OS, Rec->getValueAsInt("OpIndex"));
320 
321   if (Rec->isSubClassOf("CheckIsImmOperand"))
322     return expandCheckIsImmOperand(OS, Rec->getValueAsInt("OpIndex"));
323 
324   if (Rec->isSubClassOf("CheckRegOperand"))
325     return expandCheckRegOperand(OS, Rec->getValueAsInt("OpIndex"),
326                                  Rec->getValueAsDef("Reg"),
327                                  Rec->getValueAsString("FunctionMapper"));
328 
329   if (Rec->isSubClassOf("CheckRegOperandSimple"))
330     return expandCheckRegOperandSimple(OS, Rec->getValueAsInt("OpIndex"),
331                                        Rec->getValueAsString("FunctionMapper"));
332 
333   if (Rec->isSubClassOf("CheckInvalidRegOperand"))
334     return expandCheckInvalidRegOperand(OS, Rec->getValueAsInt("OpIndex"));
335 
336   if (Rec->isSubClassOf("CheckImmOperand"))
337     return expandCheckImmOperand(OS, Rec->getValueAsInt("OpIndex"),
338                                  Rec->getValueAsInt("ImmVal"),
339                                  Rec->getValueAsString("FunctionMapper"));
340 
341   if (Rec->isSubClassOf("CheckImmOperand_s"))
342     return expandCheckImmOperand(OS, Rec->getValueAsInt("OpIndex"),
343                                  Rec->getValueAsString("ImmVal"),
344                                  Rec->getValueAsString("FunctionMapper"));
345 
346   if (Rec->isSubClassOf("CheckImmOperandSimple"))
347     return expandCheckImmOperandSimple(OS, Rec->getValueAsInt("OpIndex"),
348                                        Rec->getValueAsString("FunctionMapper"));
349 
350   if (Rec->isSubClassOf("CheckSameRegOperand"))
351     return expandCheckSameRegOperand(OS, Rec->getValueAsInt("FirstIndex"),
352                                      Rec->getValueAsInt("SecondIndex"));
353 
354   if (Rec->isSubClassOf("CheckNumOperands"))
355     return expandCheckNumOperands(OS, Rec->getValueAsInt("NumOps"));
356 
357   if (Rec->isSubClassOf("CheckPseudo"))
358     return expandCheckPseudo(OS, Rec->getValueAsListOfDefs("ValidOpcodes"));
359 
360   if (Rec->isSubClassOf("CheckOpcode"))
361     return expandCheckOpcode(OS, Rec->getValueAsListOfDefs("ValidOpcodes"));
362 
363   if (Rec->isSubClassOf("CheckAll"))
364     return expandPredicateSequence(OS, Rec->getValueAsListOfDefs("Predicates"),
365                                    /* AllOf */ true);
366 
367   if (Rec->isSubClassOf("CheckAny"))
368     return expandPredicateSequence(OS, Rec->getValueAsListOfDefs("Predicates"),
369                                    /* AllOf */ false);
370 
371   if (Rec->isSubClassOf("CheckFunctionPredicate")) {
372     return expandCheckFunctionPredicate(
373         OS, Rec->getValueAsString("MCInstFnName"),
374         Rec->getValueAsString("MachineInstrFnName"));
375   }
376 
377   if (Rec->isSubClassOf("CheckFunctionPredicateWithTII")) {
378     return expandCheckFunctionPredicateWithTII(
379         OS, Rec->getValueAsString("MCInstFnName"),
380         Rec->getValueAsString("MachineInstrFnName"),
381         Rec->getValueAsString("TIIPtrName"));
382   }
383 
384   if (Rec->isSubClassOf("CheckNonPortable"))
385     return expandCheckNonPortable(OS, Rec->getValueAsString("CodeBlock"));
386 
387   if (Rec->isSubClassOf("TIIPredicate"))
388     return expandTIIFunctionCall(OS, Rec->getValueAsString("FunctionName"));
389 
390   llvm_unreachable("No known rules to expand this MCInstPredicate");
391 }
392 
393 void STIPredicateExpander::expandHeader(raw_ostream &OS,
394                                         const STIPredicateFunction &Fn) {
395   const Record *Rec = Fn.getDeclaration();
396   StringRef FunctionName = Rec->getValueAsString("Name");
397 
398   OS.indent(getIndentLevel() * 2);
399   OS << "bool ";
400   if (shouldExpandDefinition())
401     OS << getClassPrefix() << "::";
402   OS << FunctionName << "(";
403   if (shouldExpandForMC())
404     OS << "const MCInst " << (isByRef() ? "&" : "*") << "MI";
405   else
406     OS << "const MachineInstr " << (isByRef() ? "&" : "*") << "MI";
407   if (Rec->getValueAsBit("UpdatesOpcodeMask"))
408     OS << ", APInt &Mask";
409   OS << (shouldExpandForMC() ? ", unsigned ProcessorID) const " : ") const ");
410   if (shouldExpandDefinition()) {
411     OS << "{\n";
412     return;
413   }
414 
415   if (Rec->getValueAsBit("OverridesBaseClassMember"))
416     OS << "override";
417   OS << ";\n";
418 }
419 
420 void STIPredicateExpander::expandPrologue(raw_ostream &OS,
421                                           const STIPredicateFunction &Fn) {
422   RecVec Delegates = Fn.getDeclaration()->getValueAsListOfDefs("Delegates");
423   bool UpdatesOpcodeMask =
424       Fn.getDeclaration()->getValueAsBit("UpdatesOpcodeMask");
425 
426   increaseIndentLevel();
427   unsigned IndentLevel = getIndentLevel();
428   for (const Record *Delegate : Delegates) {
429     OS.indent(IndentLevel * 2);
430     OS << "if (" << Delegate->getValueAsString("Name") << "(MI";
431     if (UpdatesOpcodeMask)
432       OS << ", Mask";
433     if (shouldExpandForMC())
434       OS << ", ProcessorID";
435     OS << "))\n";
436     OS.indent((1 + IndentLevel) * 2);
437     OS << "return true;\n\n";
438   }
439 
440   if (shouldExpandForMC())
441     return;
442 
443   OS.indent(IndentLevel * 2);
444   OS << "unsigned ProcessorID = getSchedModel().getProcessorID();\n";
445 }
446 
447 void STIPredicateExpander::expandOpcodeGroup(raw_ostream &OS, const OpcodeGroup &Group,
448                                              bool ShouldUpdateOpcodeMask) {
449   const OpcodeInfo &OI = Group.getOpcodeInfo();
450   for (const PredicateInfo &PI : OI.getPredicates()) {
451     const APInt &ProcModelMask = PI.ProcModelMask;
452     bool FirstProcID = true;
453     for (unsigned I = 0, E = ProcModelMask.getActiveBits(); I < E; ++I) {
454       if (!ProcModelMask[I])
455         continue;
456 
457       if (FirstProcID) {
458         OS.indent(getIndentLevel() * 2);
459         OS << "if (ProcessorID == " << I;
460       } else {
461         OS << " || ProcessorID == " << I;
462       }
463       FirstProcID = false;
464     }
465 
466     OS << ") {\n";
467 
468     increaseIndentLevel();
469     OS.indent(getIndentLevel() * 2);
470     if (ShouldUpdateOpcodeMask) {
471       if (PI.OperandMask.isZero())
472         OS << "Mask.clearAllBits();\n";
473       else
474         OS << "Mask = " << PI.OperandMask << ";\n";
475       OS.indent(getIndentLevel() * 2);
476     }
477     OS << "return ";
478     expandPredicate(OS, PI.Predicate);
479     OS << ";\n";
480     decreaseIndentLevel();
481     OS.indent(getIndentLevel() * 2);
482     OS << "}\n";
483   }
484 }
485 
486 void STIPredicateExpander::expandBody(raw_ostream &OS,
487                                       const STIPredicateFunction &Fn) {
488   bool UpdatesOpcodeMask =
489       Fn.getDeclaration()->getValueAsBit("UpdatesOpcodeMask");
490 
491   unsigned IndentLevel = getIndentLevel();
492   OS.indent(IndentLevel * 2);
493   OS << "switch(MI" << (isByRef() ? "." : "->") << "getOpcode()) {\n";
494   OS.indent(IndentLevel * 2);
495   OS << "default:\n";
496   OS.indent(IndentLevel * 2);
497   OS << "  break;";
498 
499   for (const OpcodeGroup &Group : Fn.getGroups()) {
500     for (const Record *Opcode : Group.getOpcodes()) {
501       OS << '\n';
502       OS.indent(IndentLevel * 2);
503       OS << "case " << getTargetName() << "::" << Opcode->getName() << ":";
504     }
505 
506     OS << '\n';
507     increaseIndentLevel();
508     expandOpcodeGroup(OS, Group, UpdatesOpcodeMask);
509 
510     OS.indent(getIndentLevel() * 2);
511     OS << "break;\n";
512     decreaseIndentLevel();
513   }
514 
515   OS.indent(IndentLevel * 2);
516   OS << "}\n";
517 }
518 
519 void STIPredicateExpander::expandEpilogue(raw_ostream &OS,
520                                           const STIPredicateFunction &Fn) {
521   OS << '\n';
522   OS.indent(getIndentLevel() * 2);
523   OS << "return ";
524   expandPredicate(OS, Fn.getDefaultReturnPredicate());
525   OS << ";\n";
526 
527   decreaseIndentLevel();
528   OS.indent(getIndentLevel() * 2);
529   StringRef FunctionName = Fn.getDeclaration()->getValueAsString("Name");
530   OS << "} // " << ClassPrefix << "::" << FunctionName << "\n\n";
531 }
532 
533 void STIPredicateExpander::expandSTIPredicate(raw_ostream &OS,
534                                               const STIPredicateFunction &Fn) {
535   const Record *Rec = Fn.getDeclaration();
536   if (shouldExpandForMC() && !Rec->getValueAsBit("ExpandForMC"))
537     return;
538 
539   expandHeader(OS, Fn);
540   if (shouldExpandDefinition()) {
541     expandPrologue(OS, Fn);
542     expandBody(OS, Fn);
543     expandEpilogue(OS, Fn);
544   }
545 }
546 
547 } // namespace llvm
548