xref: /freebsd-src/contrib/llvm-project/llvm/utils/TableGen/CompressInstEmitter.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1349cc55cSDimitry Andric //===-------- CompressInstEmitter.cpp - Generator for Compression ---------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric // CompressInstEmitter implements a tablegen-driven CompressPat based
8349cc55cSDimitry Andric // Instruction Compression mechanism.
9349cc55cSDimitry Andric //
10349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
11349cc55cSDimitry Andric //
12349cc55cSDimitry Andric // CompressInstEmitter implements a tablegen-driven CompressPat Instruction
13349cc55cSDimitry Andric // Compression mechanism for generating compressed instructions from the
14349cc55cSDimitry Andric // expanded instruction form.
15349cc55cSDimitry Andric 
16349cc55cSDimitry Andric // This tablegen backend processes CompressPat declarations in a
17349cc55cSDimitry Andric // td file and generates all the required checks to validate the pattern
18349cc55cSDimitry Andric // declarations; validate the input and output operands to generate the correct
19349cc55cSDimitry Andric // compressed instructions. The checks include validating  different types of
20349cc55cSDimitry Andric // operands; register operands, immediate operands, fixed register and fixed
21349cc55cSDimitry Andric // immediate inputs.
22349cc55cSDimitry Andric //
23349cc55cSDimitry Andric // Example:
24349cc55cSDimitry Andric // /// Defines a Pat match between compressed and uncompressed instruction.
25349cc55cSDimitry Andric // /// The relationship and helper function generation are handled by
26349cc55cSDimitry Andric // /// CompressInstEmitter backend.
27349cc55cSDimitry Andric // class CompressPat<dag input, dag output, list<Predicate> predicates = []> {
28349cc55cSDimitry Andric //   /// Uncompressed instruction description.
29349cc55cSDimitry Andric //   dag Input  = input;
30349cc55cSDimitry Andric //   /// Compressed instruction description.
31349cc55cSDimitry Andric //   dag Output = output;
32349cc55cSDimitry Andric //   /// Predicates that must be true for this to match.
33349cc55cSDimitry Andric //   list<Predicate> Predicates = predicates;
34349cc55cSDimitry Andric //   /// Duplicate match when tied operand is just different.
35349cc55cSDimitry Andric //   bit isCompressOnly = false;
36349cc55cSDimitry Andric // }
37349cc55cSDimitry Andric //
38349cc55cSDimitry Andric // let Predicates = [HasStdExtC] in {
39349cc55cSDimitry Andric // def : CompressPat<(ADD GPRNoX0:$rs1, GPRNoX0:$rs1, GPRNoX0:$rs2),
40349cc55cSDimitry Andric //                   (C_ADD GPRNoX0:$rs1, GPRNoX0:$rs2)>;
41349cc55cSDimitry Andric // }
42349cc55cSDimitry Andric //
43349cc55cSDimitry Andric // The <TargetName>GenCompressInstEmitter.inc is an auto-generated header
44349cc55cSDimitry Andric // file which exports two functions for compressing/uncompressing MCInst
45349cc55cSDimitry Andric // instructions, plus some helper functions:
46349cc55cSDimitry Andric //
47349cc55cSDimitry Andric // bool compressInst(MCInst &OutInst, const MCInst &MI,
48*bdd1243dSDimitry Andric //                   const MCSubtargetInfo &STI);
49349cc55cSDimitry Andric //
50349cc55cSDimitry Andric // bool uncompressInst(MCInst &OutInst, const MCInst &MI,
51349cc55cSDimitry Andric //                     const MCSubtargetInfo &STI);
52349cc55cSDimitry Andric //
53349cc55cSDimitry Andric // In addition, it exports a function for checking whether
54349cc55cSDimitry Andric // an instruction is compressable:
55349cc55cSDimitry Andric //
56349cc55cSDimitry Andric // bool isCompressibleInst(const MachineInstr& MI,
57*bdd1243dSDimitry Andric //                         const <TargetName>Subtarget &STI);
58349cc55cSDimitry Andric //
59349cc55cSDimitry Andric // The clients that include this auto-generated header file and
60349cc55cSDimitry Andric // invoke these functions can compress an instruction before emitting
61349cc55cSDimitry Andric // it in the target-specific ASM or ELF streamer or can uncompress
62349cc55cSDimitry Andric // an instruction before printing it when the expanded instruction
63349cc55cSDimitry Andric // format aliases is favored.
64349cc55cSDimitry Andric 
65349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
66349cc55cSDimitry Andric 
67349cc55cSDimitry Andric #include "CodeGenInstruction.h"
68349cc55cSDimitry Andric #include "CodeGenTarget.h"
69349cc55cSDimitry Andric #include "llvm/ADT/IndexedMap.h"
70349cc55cSDimitry Andric #include "llvm/ADT/SmallVector.h"
71349cc55cSDimitry Andric #include "llvm/ADT/StringMap.h"
72349cc55cSDimitry Andric #include "llvm/Support/Debug.h"
73349cc55cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
74349cc55cSDimitry Andric #include "llvm/TableGen/Error.h"
75349cc55cSDimitry Andric #include "llvm/TableGen/Record.h"
76349cc55cSDimitry Andric #include "llvm/TableGen/TableGenBackend.h"
77349cc55cSDimitry Andric #include <set>
78349cc55cSDimitry Andric #include <vector>
79349cc55cSDimitry Andric using namespace llvm;
80349cc55cSDimitry Andric 
81349cc55cSDimitry Andric #define DEBUG_TYPE "compress-inst-emitter"
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric namespace {
84349cc55cSDimitry Andric class CompressInstEmitter {
85349cc55cSDimitry Andric   struct OpData {
86349cc55cSDimitry Andric     enum MapKind { Operand, Imm, Reg };
87349cc55cSDimitry Andric     MapKind Kind;
88349cc55cSDimitry Andric     union {
89349cc55cSDimitry Andric       // Operand number mapped to.
90349cc55cSDimitry Andric       unsigned Operand;
91349cc55cSDimitry Andric       // Integer immediate value.
92349cc55cSDimitry Andric       int64_t Imm;
93349cc55cSDimitry Andric       // Physical register.
94349cc55cSDimitry Andric       Record *Reg;
95349cc55cSDimitry Andric     } Data;
96349cc55cSDimitry Andric     // Tied operand index within the instruction.
97349cc55cSDimitry Andric     int TiedOpIdx = -1;
98349cc55cSDimitry Andric   };
99349cc55cSDimitry Andric   struct CompressPat {
100349cc55cSDimitry Andric     // The source instruction definition.
101349cc55cSDimitry Andric     CodeGenInstruction Source;
102349cc55cSDimitry Andric     // The destination instruction to transform to.
103349cc55cSDimitry Andric     CodeGenInstruction Dest;
104349cc55cSDimitry Andric     // Required target features to enable pattern.
105349cc55cSDimitry Andric     std::vector<Record *> PatReqFeatures;
106349cc55cSDimitry Andric     // Maps operands in the Source Instruction to
107349cc55cSDimitry Andric     IndexedMap<OpData> SourceOperandMap;
108349cc55cSDimitry Andric     // the corresponding Dest instruction operand.
109349cc55cSDimitry Andric     // Maps operands in the Dest Instruction
110349cc55cSDimitry Andric     // to the corresponding Source instruction operand.
111349cc55cSDimitry Andric     IndexedMap<OpData> DestOperandMap;
112349cc55cSDimitry Andric 
113349cc55cSDimitry Andric     bool IsCompressOnly;
114349cc55cSDimitry Andric     CompressPat(CodeGenInstruction &S, CodeGenInstruction &D,
115349cc55cSDimitry Andric                 std::vector<Record *> RF, IndexedMap<OpData> &SourceMap,
116349cc55cSDimitry Andric                 IndexedMap<OpData> &DestMap, bool IsCompressOnly)
117349cc55cSDimitry Andric         : Source(S), Dest(D), PatReqFeatures(RF), SourceOperandMap(SourceMap),
118349cc55cSDimitry Andric           DestOperandMap(DestMap), IsCompressOnly(IsCompressOnly) {}
119349cc55cSDimitry Andric   };
120349cc55cSDimitry Andric   enum EmitterType { Compress, Uncompress, CheckCompress };
121349cc55cSDimitry Andric   RecordKeeper &Records;
122349cc55cSDimitry Andric   CodeGenTarget Target;
123349cc55cSDimitry Andric   SmallVector<CompressPat, 4> CompressPatterns;
124349cc55cSDimitry Andric 
125349cc55cSDimitry Andric   void addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Inst,
126349cc55cSDimitry Andric                             IndexedMap<OpData> &OperandMap, bool IsSourceInst);
127349cc55cSDimitry Andric   void evaluateCompressPat(Record *Compress);
128349cc55cSDimitry Andric   void emitCompressInstEmitter(raw_ostream &o, EmitterType EType);
129349cc55cSDimitry Andric   bool validateTypes(Record *SubType, Record *Type, bool IsSourceInst);
130349cc55cSDimitry Andric   bool validateRegister(Record *Reg, Record *RegClass);
131349cc55cSDimitry Andric   void createDagOperandMapping(Record *Rec, StringMap<unsigned> &SourceOperands,
132349cc55cSDimitry Andric                                StringMap<unsigned> &DestOperands,
133349cc55cSDimitry Andric                                DagInit *SourceDag, DagInit *DestDag,
134349cc55cSDimitry Andric                                IndexedMap<OpData> &SourceOperandMap);
135349cc55cSDimitry Andric 
136349cc55cSDimitry Andric   void createInstOperandMapping(Record *Rec, DagInit *SourceDag,
137349cc55cSDimitry Andric                                 DagInit *DestDag,
138349cc55cSDimitry Andric                                 IndexedMap<OpData> &SourceOperandMap,
139349cc55cSDimitry Andric                                 IndexedMap<OpData> &DestOperandMap,
140349cc55cSDimitry Andric                                 StringMap<unsigned> &SourceOperands,
141349cc55cSDimitry Andric                                 CodeGenInstruction &DestInst);
142349cc55cSDimitry Andric 
143349cc55cSDimitry Andric public:
144349cc55cSDimitry Andric   CompressInstEmitter(RecordKeeper &R) : Records(R), Target(R) {}
145349cc55cSDimitry Andric 
146349cc55cSDimitry Andric   void run(raw_ostream &o);
147349cc55cSDimitry Andric };
148349cc55cSDimitry Andric } // End anonymous namespace.
149349cc55cSDimitry Andric 
150349cc55cSDimitry Andric bool CompressInstEmitter::validateRegister(Record *Reg, Record *RegClass) {
151349cc55cSDimitry Andric   assert(Reg->isSubClassOf("Register") && "Reg record should be a Register");
152349cc55cSDimitry Andric   assert(RegClass->isSubClassOf("RegisterClass") &&
153349cc55cSDimitry Andric          "RegClass record should be a RegisterClass");
154349cc55cSDimitry Andric   const CodeGenRegisterClass &RC = Target.getRegisterClass(RegClass);
155349cc55cSDimitry Andric   const CodeGenRegister *R = Target.getRegisterByName(Reg->getName().lower());
156349cc55cSDimitry Andric   assert((R != nullptr) && "Register not defined!!");
157349cc55cSDimitry Andric   return RC.contains(R);
158349cc55cSDimitry Andric }
159349cc55cSDimitry Andric 
160349cc55cSDimitry Andric bool CompressInstEmitter::validateTypes(Record *DagOpType, Record *InstOpType,
161349cc55cSDimitry Andric                                         bool IsSourceInst) {
162349cc55cSDimitry Andric   if (DagOpType == InstOpType)
163349cc55cSDimitry Andric     return true;
164349cc55cSDimitry Andric   // Only source instruction operands are allowed to not match Input Dag
165349cc55cSDimitry Andric   // operands.
166349cc55cSDimitry Andric   if (!IsSourceInst)
167349cc55cSDimitry Andric     return false;
168349cc55cSDimitry Andric 
169349cc55cSDimitry Andric   if (DagOpType->isSubClassOf("RegisterClass") &&
170349cc55cSDimitry Andric       InstOpType->isSubClassOf("RegisterClass")) {
171349cc55cSDimitry Andric     const CodeGenRegisterClass &RC = Target.getRegisterClass(InstOpType);
172349cc55cSDimitry Andric     const CodeGenRegisterClass &SubRC = Target.getRegisterClass(DagOpType);
173349cc55cSDimitry Andric     return RC.hasSubClass(&SubRC);
174349cc55cSDimitry Andric   }
175349cc55cSDimitry Andric 
176349cc55cSDimitry Andric   // At this point either or both types are not registers, reject the pattern.
177349cc55cSDimitry Andric   if (DagOpType->isSubClassOf("RegisterClass") ||
178349cc55cSDimitry Andric       InstOpType->isSubClassOf("RegisterClass"))
179349cc55cSDimitry Andric     return false;
180349cc55cSDimitry Andric 
181349cc55cSDimitry Andric   // Let further validation happen when compress()/uncompress() functions are
182349cc55cSDimitry Andric   // invoked.
183349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << (IsSourceInst ? "Input" : "Output")
184349cc55cSDimitry Andric                     << " Dag Operand Type: '" << DagOpType->getName()
185349cc55cSDimitry Andric                     << "' and "
186349cc55cSDimitry Andric                     << "Instruction Operand Type: '" << InstOpType->getName()
187349cc55cSDimitry Andric                     << "' can't be checked at pattern validation time!\n");
188349cc55cSDimitry Andric   return true;
189349cc55cSDimitry Andric }
190349cc55cSDimitry Andric 
191349cc55cSDimitry Andric /// The patterns in the Dag contain different types of operands:
192349cc55cSDimitry Andric /// Register operands, e.g.: GPRC:$rs1; Fixed registers, e.g: X1; Immediate
193349cc55cSDimitry Andric /// operands, e.g.: simm6:$imm; Fixed immediate operands, e.g.: 0. This function
194349cc55cSDimitry Andric /// maps Dag operands to its corresponding instruction operands. For register
195349cc55cSDimitry Andric /// operands and fixed registers it expects the Dag operand type to be contained
196349cc55cSDimitry Andric /// in the instantiated instruction operand type. For immediate operands and
197349cc55cSDimitry Andric /// immediates no validation checks are enforced at pattern validation time.
198349cc55cSDimitry Andric void CompressInstEmitter::addDagOperandMapping(Record *Rec, DagInit *Dag,
199349cc55cSDimitry Andric                                                CodeGenInstruction &Inst,
200349cc55cSDimitry Andric                                                IndexedMap<OpData> &OperandMap,
201349cc55cSDimitry Andric                                                bool IsSourceInst) {
202349cc55cSDimitry Andric   // TiedCount keeps track of the number of operands skipped in Inst
203349cc55cSDimitry Andric   // operands list to get to the corresponding Dag operand. This is
204349cc55cSDimitry Andric   // necessary because the number of operands in Inst might be greater
205349cc55cSDimitry Andric   // than number of operands in the Dag due to how tied operands
206349cc55cSDimitry Andric   // are represented.
207349cc55cSDimitry Andric   unsigned TiedCount = 0;
208349cc55cSDimitry Andric   for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
209349cc55cSDimitry Andric     int TiedOpIdx = Inst.Operands[i].getTiedRegister();
210349cc55cSDimitry Andric     if (-1 != TiedOpIdx) {
211349cc55cSDimitry Andric       // Set the entry in OperandMap for the tied operand we're skipping.
212349cc55cSDimitry Andric       OperandMap[i].Kind = OperandMap[TiedOpIdx].Kind;
213349cc55cSDimitry Andric       OperandMap[i].Data = OperandMap[TiedOpIdx].Data;
214349cc55cSDimitry Andric       TiedCount++;
215349cc55cSDimitry Andric       continue;
216349cc55cSDimitry Andric     }
217349cc55cSDimitry Andric     if (DefInit *DI = dyn_cast<DefInit>(Dag->getArg(i - TiedCount))) {
218349cc55cSDimitry Andric       if (DI->getDef()->isSubClassOf("Register")) {
219349cc55cSDimitry Andric         // Check if the fixed register belongs to the Register class.
220349cc55cSDimitry Andric         if (!validateRegister(DI->getDef(), Inst.Operands[i].Rec))
221349cc55cSDimitry Andric           PrintFatalError(Rec->getLoc(),
222349cc55cSDimitry Andric                           "Error in Dag '" + Dag->getAsString() +
223349cc55cSDimitry Andric                               "'Register: '" + DI->getDef()->getName() +
224349cc55cSDimitry Andric                               "' is not in register class '" +
225349cc55cSDimitry Andric                               Inst.Operands[i].Rec->getName() + "'");
226349cc55cSDimitry Andric         OperandMap[i].Kind = OpData::Reg;
227349cc55cSDimitry Andric         OperandMap[i].Data.Reg = DI->getDef();
228349cc55cSDimitry Andric         continue;
229349cc55cSDimitry Andric       }
230349cc55cSDimitry Andric       // Validate that Dag operand type matches the type defined in the
231349cc55cSDimitry Andric       // corresponding instruction. Operands in the input Dag pattern are
232349cc55cSDimitry Andric       // allowed to be a subclass of the type specified in corresponding
233349cc55cSDimitry Andric       // instruction operand instead of being an exact match.
234349cc55cSDimitry Andric       if (!validateTypes(DI->getDef(), Inst.Operands[i].Rec, IsSourceInst))
235349cc55cSDimitry Andric         PrintFatalError(Rec->getLoc(),
236349cc55cSDimitry Andric                         "Error in Dag '" + Dag->getAsString() + "'. Operand '" +
237349cc55cSDimitry Andric                             Dag->getArgNameStr(i - TiedCount) + "' has type '" +
238349cc55cSDimitry Andric                             DI->getDef()->getName() +
239349cc55cSDimitry Andric                             "' which does not match the type '" +
240349cc55cSDimitry Andric                             Inst.Operands[i].Rec->getName() +
241349cc55cSDimitry Andric                             "' in the corresponding instruction operand!");
242349cc55cSDimitry Andric 
243349cc55cSDimitry Andric       OperandMap[i].Kind = OpData::Operand;
244349cc55cSDimitry Andric     } else if (IntInit *II = dyn_cast<IntInit>(Dag->getArg(i - TiedCount))) {
245349cc55cSDimitry Andric       // Validate that corresponding instruction operand expects an immediate.
246349cc55cSDimitry Andric       if (Inst.Operands[i].Rec->isSubClassOf("RegisterClass"))
247349cc55cSDimitry Andric         PrintFatalError(
248349cc55cSDimitry Andric             Rec->getLoc(),
249349cc55cSDimitry Andric             "Error in Dag '" + Dag->getAsString() + "' Found immediate: '" +
250349cc55cSDimitry Andric                 II->getAsString() +
251349cc55cSDimitry Andric                 "' but corresponding instruction operand expected a register!");
252349cc55cSDimitry Andric       // No pattern validation check possible for values of fixed immediate.
253349cc55cSDimitry Andric       OperandMap[i].Kind = OpData::Imm;
254349cc55cSDimitry Andric       OperandMap[i].Data.Imm = II->getValue();
255349cc55cSDimitry Andric       LLVM_DEBUG(
256349cc55cSDimitry Andric           dbgs() << "  Found immediate '" << II->getValue() << "' at "
257349cc55cSDimitry Andric                  << (IsSourceInst ? "input " : "output ")
258349cc55cSDimitry Andric                  << "Dag. No validation time check possible for values of "
259349cc55cSDimitry Andric                     "fixed immediate.\n");
260349cc55cSDimitry Andric     } else
261349cc55cSDimitry Andric       llvm_unreachable("Unhandled CompressPat argument type!");
262349cc55cSDimitry Andric   }
263349cc55cSDimitry Andric }
264349cc55cSDimitry Andric 
265349cc55cSDimitry Andric // Verify the Dag operand count is enough to build an instruction.
266349cc55cSDimitry Andric static bool verifyDagOpCount(CodeGenInstruction &Inst, DagInit *Dag,
267349cc55cSDimitry Andric                              bool IsSource) {
268349cc55cSDimitry Andric   if (Dag->getNumArgs() == Inst.Operands.size())
269349cc55cSDimitry Andric     return true;
270349cc55cSDimitry Andric   // Source instructions are non compressed instructions and don't have tied
271349cc55cSDimitry Andric   // operands.
272349cc55cSDimitry Andric   if (IsSource)
273349cc55cSDimitry Andric     PrintFatalError(Inst.TheDef->getLoc(),
274349cc55cSDimitry Andric                     "Input operands for Inst '" + Inst.TheDef->getName() +
275349cc55cSDimitry Andric                         "' and input Dag operand count mismatch");
276349cc55cSDimitry Andric   // The Dag can't have more arguments than the Instruction.
277349cc55cSDimitry Andric   if (Dag->getNumArgs() > Inst.Operands.size())
278349cc55cSDimitry Andric     PrintFatalError(Inst.TheDef->getLoc(),
279349cc55cSDimitry Andric                     "Inst '" + Inst.TheDef->getName() +
280349cc55cSDimitry Andric                         "' and Dag operand count mismatch");
281349cc55cSDimitry Andric 
282349cc55cSDimitry Andric   // The Instruction might have tied operands so the Dag might have
283349cc55cSDimitry Andric   //  a fewer operand count.
284349cc55cSDimitry Andric   unsigned RealCount = Inst.Operands.size();
285349cc55cSDimitry Andric   for (const auto &Operand : Inst.Operands)
286349cc55cSDimitry Andric     if (Operand.getTiedRegister() != -1)
287349cc55cSDimitry Andric       --RealCount;
288349cc55cSDimitry Andric 
289349cc55cSDimitry Andric   if (Dag->getNumArgs() != RealCount)
290349cc55cSDimitry Andric     PrintFatalError(Inst.TheDef->getLoc(),
291349cc55cSDimitry Andric                     "Inst '" + Inst.TheDef->getName() +
292349cc55cSDimitry Andric                         "' and Dag operand count mismatch");
293349cc55cSDimitry Andric   return true;
294349cc55cSDimitry Andric }
295349cc55cSDimitry Andric 
296349cc55cSDimitry Andric static bool validateArgsTypes(Init *Arg1, Init *Arg2) {
297349cc55cSDimitry Andric   return cast<DefInit>(Arg1)->getDef() == cast<DefInit>(Arg2)->getDef();
298349cc55cSDimitry Andric }
299349cc55cSDimitry Andric 
300349cc55cSDimitry Andric // Creates a mapping between the operand name in the Dag (e.g. $rs1) and
301349cc55cSDimitry Andric // its index in the list of Dag operands and checks that operands with the same
302349cc55cSDimitry Andric // name have the same types. For example in 'C_ADD $rs1, $rs2' we generate the
303349cc55cSDimitry Andric // mapping $rs1 --> 0, $rs2 ---> 1. If the operand appears twice in the (tied)
304349cc55cSDimitry Andric // same Dag we use the last occurrence for indexing.
305349cc55cSDimitry Andric void CompressInstEmitter::createDagOperandMapping(
306349cc55cSDimitry Andric     Record *Rec, StringMap<unsigned> &SourceOperands,
307349cc55cSDimitry Andric     StringMap<unsigned> &DestOperands, DagInit *SourceDag, DagInit *DestDag,
308349cc55cSDimitry Andric     IndexedMap<OpData> &SourceOperandMap) {
309349cc55cSDimitry Andric   for (unsigned i = 0; i < DestDag->getNumArgs(); ++i) {
310349cc55cSDimitry Andric     // Skip fixed immediates and registers, they were handled in
311349cc55cSDimitry Andric     // addDagOperandMapping.
312349cc55cSDimitry Andric     if ("" == DestDag->getArgNameStr(i))
313349cc55cSDimitry Andric       continue;
314349cc55cSDimitry Andric     DestOperands[DestDag->getArgNameStr(i)] = i;
315349cc55cSDimitry Andric   }
316349cc55cSDimitry Andric 
317349cc55cSDimitry Andric   for (unsigned i = 0; i < SourceDag->getNumArgs(); ++i) {
318349cc55cSDimitry Andric     // Skip fixed immediates and registers, they were handled in
319349cc55cSDimitry Andric     // addDagOperandMapping.
320349cc55cSDimitry Andric     if ("" == SourceDag->getArgNameStr(i))
321349cc55cSDimitry Andric       continue;
322349cc55cSDimitry Andric 
323349cc55cSDimitry Andric     StringMap<unsigned>::iterator it =
324349cc55cSDimitry Andric         SourceOperands.find(SourceDag->getArgNameStr(i));
325349cc55cSDimitry Andric     if (it != SourceOperands.end()) {
326349cc55cSDimitry Andric       // Operand sharing the same name in the Dag should be mapped as tied.
327349cc55cSDimitry Andric       SourceOperandMap[i].TiedOpIdx = it->getValue();
328349cc55cSDimitry Andric       if (!validateArgsTypes(SourceDag->getArg(it->getValue()),
329349cc55cSDimitry Andric                              SourceDag->getArg(i)))
330349cc55cSDimitry Andric         PrintFatalError(Rec->getLoc(),
331349cc55cSDimitry Andric                         "Input Operand '" + SourceDag->getArgNameStr(i) +
332349cc55cSDimitry Andric                             "' has a mismatched tied operand!\n");
333349cc55cSDimitry Andric     }
334349cc55cSDimitry Andric     it = DestOperands.find(SourceDag->getArgNameStr(i));
335349cc55cSDimitry Andric     if (it == DestOperands.end())
336349cc55cSDimitry Andric       PrintFatalError(Rec->getLoc(), "Operand " + SourceDag->getArgNameStr(i) +
337349cc55cSDimitry Andric                                          " defined in Input Dag but not used in"
338349cc55cSDimitry Andric                                          " Output Dag!\n");
339349cc55cSDimitry Andric     // Input Dag operand types must match output Dag operand type.
340349cc55cSDimitry Andric     if (!validateArgsTypes(DestDag->getArg(it->getValue()),
341349cc55cSDimitry Andric                            SourceDag->getArg(i)))
342349cc55cSDimitry Andric       PrintFatalError(Rec->getLoc(), "Type mismatch between Input and "
343349cc55cSDimitry Andric                                      "Output Dag operand '" +
344349cc55cSDimitry Andric                                          SourceDag->getArgNameStr(i) + "'!");
345349cc55cSDimitry Andric     SourceOperands[SourceDag->getArgNameStr(i)] = i;
346349cc55cSDimitry Andric   }
347349cc55cSDimitry Andric }
348349cc55cSDimitry Andric 
349349cc55cSDimitry Andric /// Map operand names in the Dag to their index in both corresponding input and
350349cc55cSDimitry Andric /// output instructions. Validate that operands defined in the input are
351349cc55cSDimitry Andric /// used in the output pattern while populating the maps.
352349cc55cSDimitry Andric void CompressInstEmitter::createInstOperandMapping(
353349cc55cSDimitry Andric     Record *Rec, DagInit *SourceDag, DagInit *DestDag,
354349cc55cSDimitry Andric     IndexedMap<OpData> &SourceOperandMap, IndexedMap<OpData> &DestOperandMap,
355349cc55cSDimitry Andric     StringMap<unsigned> &SourceOperands, CodeGenInstruction &DestInst) {
356349cc55cSDimitry Andric   // TiedCount keeps track of the number of operands skipped in Inst
357349cc55cSDimitry Andric   // operands list to get to the corresponding Dag operand.
358349cc55cSDimitry Andric   unsigned TiedCount = 0;
359349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "  Operand mapping:\n  Source   Dest\n");
360349cc55cSDimitry Andric   for (unsigned i = 0, e = DestInst.Operands.size(); i != e; ++i) {
361349cc55cSDimitry Andric     int TiedInstOpIdx = DestInst.Operands[i].getTiedRegister();
362349cc55cSDimitry Andric     if (TiedInstOpIdx != -1) {
363349cc55cSDimitry Andric       ++TiedCount;
364349cc55cSDimitry Andric       DestOperandMap[i].Data = DestOperandMap[TiedInstOpIdx].Data;
365349cc55cSDimitry Andric       DestOperandMap[i].Kind = DestOperandMap[TiedInstOpIdx].Kind;
366349cc55cSDimitry Andric       if (DestOperandMap[i].Kind == OpData::Operand)
367349cc55cSDimitry Andric         // No need to fill the SourceOperandMap here since it was mapped to
368349cc55cSDimitry Andric         // destination operand 'TiedInstOpIdx' in a previous iteration.
369349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "    " << DestOperandMap[i].Data.Operand
370349cc55cSDimitry Andric                           << " ====> " << i
371349cc55cSDimitry Andric                           << "  Dest operand tied with operand '"
372349cc55cSDimitry Andric                           << TiedInstOpIdx << "'\n");
373349cc55cSDimitry Andric       continue;
374349cc55cSDimitry Andric     }
375349cc55cSDimitry Andric     // Skip fixed immediates and registers, they were handled in
376349cc55cSDimitry Andric     // addDagOperandMapping.
377349cc55cSDimitry Andric     if (DestOperandMap[i].Kind != OpData::Operand)
378349cc55cSDimitry Andric       continue;
379349cc55cSDimitry Andric 
380349cc55cSDimitry Andric     unsigned DagArgIdx = i - TiedCount;
381349cc55cSDimitry Andric     StringMap<unsigned>::iterator SourceOp =
382349cc55cSDimitry Andric         SourceOperands.find(DestDag->getArgNameStr(DagArgIdx));
383349cc55cSDimitry Andric     if (SourceOp == SourceOperands.end())
384349cc55cSDimitry Andric       PrintFatalError(Rec->getLoc(),
385349cc55cSDimitry Andric                       "Output Dag operand '" +
386349cc55cSDimitry Andric                           DestDag->getArgNameStr(DagArgIdx) +
387349cc55cSDimitry Andric                           "' has no matching input Dag operand.");
388349cc55cSDimitry Andric 
389349cc55cSDimitry Andric     assert(DestDag->getArgNameStr(DagArgIdx) ==
390349cc55cSDimitry Andric                SourceDag->getArgNameStr(SourceOp->getValue()) &&
391349cc55cSDimitry Andric            "Incorrect operand mapping detected!\n");
392349cc55cSDimitry Andric     DestOperandMap[i].Data.Operand = SourceOp->getValue();
393349cc55cSDimitry Andric     SourceOperandMap[SourceOp->getValue()].Data.Operand = i;
394349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "    " << SourceOp->getValue() << " ====> " << i
395349cc55cSDimitry Andric                       << "\n");
396349cc55cSDimitry Andric   }
397349cc55cSDimitry Andric }
398349cc55cSDimitry Andric 
399349cc55cSDimitry Andric /// Validates the CompressPattern and create operand mapping.
400349cc55cSDimitry Andric /// These are the checks to validate a CompressPat pattern declarations.
401349cc55cSDimitry Andric /// Error out with message under these conditions:
402349cc55cSDimitry Andric /// - Dag Input opcode is an expanded instruction and Dag Output opcode is a
403349cc55cSDimitry Andric ///   compressed instruction.
404349cc55cSDimitry Andric /// - Operands in Dag Input must be all used in Dag Output.
405349cc55cSDimitry Andric ///   Register Operand type in Dag Input Type  must be contained in the
406349cc55cSDimitry Andric ///   corresponding Source Instruction type.
407349cc55cSDimitry Andric /// - Register Operand type in Dag Input must be the  same as in  Dag Ouput.
408349cc55cSDimitry Andric /// - Register Operand type in  Dag Output must be the same  as the
409349cc55cSDimitry Andric ///   corresponding Destination Inst type.
410349cc55cSDimitry Andric /// - Immediate Operand type in Dag Input must be the same as in Dag Ouput.
411349cc55cSDimitry Andric /// - Immediate Operand type in Dag Ouput must be the same as the corresponding
412349cc55cSDimitry Andric ///   Destination Instruction type.
413349cc55cSDimitry Andric /// - Fixed register must be contained in the corresponding Source Instruction
414349cc55cSDimitry Andric ///   type.
415349cc55cSDimitry Andric /// - Fixed register must be contained in the corresponding Destination
416349cc55cSDimitry Andric ///   Instruction type. Warning message printed under these conditions:
417349cc55cSDimitry Andric /// - Fixed immediate in Dag Input or Dag Ouput cannot be checked at this time
418349cc55cSDimitry Andric ///   and generate warning.
419349cc55cSDimitry Andric /// - Immediate operand type in Dag Input differs from the corresponding Source
420349cc55cSDimitry Andric ///   Instruction type  and generate a warning.
421349cc55cSDimitry Andric void CompressInstEmitter::evaluateCompressPat(Record *Rec) {
422349cc55cSDimitry Andric   // Validate input Dag operands.
423349cc55cSDimitry Andric   DagInit *SourceDag = Rec->getValueAsDag("Input");
424349cc55cSDimitry Andric   assert(SourceDag && "Missing 'Input' in compress pattern!");
425349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Input: " << *SourceDag << "\n");
426349cc55cSDimitry Andric 
427349cc55cSDimitry Andric   // Checking we are transforming from compressed to uncompressed instructions.
428349cc55cSDimitry Andric   Record *Operator = SourceDag->getOperatorAsDef(Rec->getLoc());
429349cc55cSDimitry Andric   CodeGenInstruction SourceInst(Operator);
430349cc55cSDimitry Andric   verifyDagOpCount(SourceInst, SourceDag, true);
431349cc55cSDimitry Andric 
432349cc55cSDimitry Andric   // Validate output Dag operands.
433349cc55cSDimitry Andric   DagInit *DestDag = Rec->getValueAsDag("Output");
434349cc55cSDimitry Andric   assert(DestDag && "Missing 'Output' in compress pattern!");
435349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Output: " << *DestDag << "\n");
436349cc55cSDimitry Andric 
437349cc55cSDimitry Andric   Record *DestOperator = DestDag->getOperatorAsDef(Rec->getLoc());
438349cc55cSDimitry Andric   CodeGenInstruction DestInst(DestOperator);
439349cc55cSDimitry Andric   verifyDagOpCount(DestInst, DestDag, false);
440349cc55cSDimitry Andric 
441349cc55cSDimitry Andric   if (Operator->getValueAsInt("Size") <= DestOperator->getValueAsInt("Size"))
442349cc55cSDimitry Andric     PrintFatalError(
443349cc55cSDimitry Andric         Rec->getLoc(),
444349cc55cSDimitry Andric         "Compressed instruction '" + DestOperator->getName() +
445349cc55cSDimitry Andric             "'is not strictly smaller than the uncompressed instruction '" +
446349cc55cSDimitry Andric             Operator->getName() + "' !");
447349cc55cSDimitry Andric 
448349cc55cSDimitry Andric   // Fill the mapping from the source to destination instructions.
449349cc55cSDimitry Andric 
450349cc55cSDimitry Andric   IndexedMap<OpData> SourceOperandMap;
451349cc55cSDimitry Andric   SourceOperandMap.grow(SourceInst.Operands.size());
452349cc55cSDimitry Andric   // Create a mapping between source Dag operands and source Inst operands.
453349cc55cSDimitry Andric   addDagOperandMapping(Rec, SourceDag, SourceInst, SourceOperandMap,
454349cc55cSDimitry Andric                        /*IsSourceInst*/ true);
455349cc55cSDimitry Andric 
456349cc55cSDimitry Andric   IndexedMap<OpData> DestOperandMap;
457349cc55cSDimitry Andric   DestOperandMap.grow(DestInst.Operands.size());
458349cc55cSDimitry Andric   // Create a mapping between destination Dag operands and destination Inst
459349cc55cSDimitry Andric   // operands.
460349cc55cSDimitry Andric   addDagOperandMapping(Rec, DestDag, DestInst, DestOperandMap,
461349cc55cSDimitry Andric                        /*IsSourceInst*/ false);
462349cc55cSDimitry Andric 
463349cc55cSDimitry Andric   StringMap<unsigned> SourceOperands;
464349cc55cSDimitry Andric   StringMap<unsigned> DestOperands;
465349cc55cSDimitry Andric   createDagOperandMapping(Rec, SourceOperands, DestOperands, SourceDag, DestDag,
466349cc55cSDimitry Andric                           SourceOperandMap);
467349cc55cSDimitry Andric   // Create operand mapping between the source and destination instructions.
468349cc55cSDimitry Andric   createInstOperandMapping(Rec, SourceDag, DestDag, SourceOperandMap,
469349cc55cSDimitry Andric                            DestOperandMap, SourceOperands, DestInst);
470349cc55cSDimitry Andric 
471349cc55cSDimitry Andric   // Get the target features for the CompressPat.
472349cc55cSDimitry Andric   std::vector<Record *> PatReqFeatures;
473349cc55cSDimitry Andric   std::vector<Record *> RF = Rec->getValueAsListOfDefs("Predicates");
474349cc55cSDimitry Andric   copy_if(RF, std::back_inserter(PatReqFeatures), [](Record *R) {
475349cc55cSDimitry Andric     return R->getValueAsBit("AssemblerMatcherPredicate");
476349cc55cSDimitry Andric   });
477349cc55cSDimitry Andric 
478349cc55cSDimitry Andric   CompressPatterns.push_back(CompressPat(SourceInst, DestInst, PatReqFeatures,
479349cc55cSDimitry Andric                                          SourceOperandMap, DestOperandMap,
480349cc55cSDimitry Andric                                          Rec->getValueAsBit("isCompressOnly")));
481349cc55cSDimitry Andric }
482349cc55cSDimitry Andric 
483349cc55cSDimitry Andric static void
484349cc55cSDimitry Andric getReqFeatures(std::set<std::pair<bool, StringRef>> &FeaturesSet,
485349cc55cSDimitry Andric                std::set<std::set<std::pair<bool, StringRef>>> &AnyOfFeatureSets,
486349cc55cSDimitry Andric                const std::vector<Record *> &ReqFeatures) {
487349cc55cSDimitry Andric   for (auto &R : ReqFeatures) {
488349cc55cSDimitry Andric     const DagInit *D = R->getValueAsDag("AssemblerCondDag");
489349cc55cSDimitry Andric     std::string CombineType = D->getOperator()->getAsString();
490349cc55cSDimitry Andric     if (CombineType != "any_of" && CombineType != "all_of")
491349cc55cSDimitry Andric       PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
492349cc55cSDimitry Andric     if (D->getNumArgs() == 0)
493349cc55cSDimitry Andric       PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
494349cc55cSDimitry Andric     bool IsOr = CombineType == "any_of";
495349cc55cSDimitry Andric     std::set<std::pair<bool, StringRef>> AnyOfSet;
496349cc55cSDimitry Andric 
497349cc55cSDimitry Andric     for (auto *Arg : D->getArgs()) {
498349cc55cSDimitry Andric       bool IsNot = false;
499349cc55cSDimitry Andric       if (auto *NotArg = dyn_cast<DagInit>(Arg)) {
500349cc55cSDimitry Andric         if (NotArg->getOperator()->getAsString() != "not" ||
501349cc55cSDimitry Andric             NotArg->getNumArgs() != 1)
502349cc55cSDimitry Andric           PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
503349cc55cSDimitry Andric         Arg = NotArg->getArg(0);
504349cc55cSDimitry Andric         IsNot = true;
505349cc55cSDimitry Andric       }
506349cc55cSDimitry Andric       if (!isa<DefInit>(Arg) ||
507349cc55cSDimitry Andric           !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))
508349cc55cSDimitry Andric         PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
509349cc55cSDimitry Andric       if (IsOr)
510349cc55cSDimitry Andric         AnyOfSet.insert({IsNot, cast<DefInit>(Arg)->getDef()->getName()});
511349cc55cSDimitry Andric       else
512349cc55cSDimitry Andric         FeaturesSet.insert({IsNot, cast<DefInit>(Arg)->getDef()->getName()});
513349cc55cSDimitry Andric     }
514349cc55cSDimitry Andric 
515349cc55cSDimitry Andric     if (IsOr)
516349cc55cSDimitry Andric       AnyOfFeatureSets.insert(AnyOfSet);
517349cc55cSDimitry Andric   }
518349cc55cSDimitry Andric }
519349cc55cSDimitry Andric 
520349cc55cSDimitry Andric static unsigned getPredicates(DenseMap<const Record *, unsigned> &PredicateMap,
521349cc55cSDimitry Andric                               std::vector<const Record *> &Predicates,
522349cc55cSDimitry Andric                               Record *Rec, StringRef Name) {
523349cc55cSDimitry Andric   unsigned &Entry = PredicateMap[Rec];
524349cc55cSDimitry Andric   if (Entry)
525349cc55cSDimitry Andric     return Entry;
526349cc55cSDimitry Andric 
527349cc55cSDimitry Andric   if (!Rec->isValueUnset(Name)) {
528349cc55cSDimitry Andric     Predicates.push_back(Rec);
529349cc55cSDimitry Andric     Entry = Predicates.size();
530349cc55cSDimitry Andric     return Entry;
531349cc55cSDimitry Andric   }
532349cc55cSDimitry Andric 
533349cc55cSDimitry Andric   PrintFatalError(Rec->getLoc(), "No " + Name +
534349cc55cSDimitry Andric                                      " predicate on this operand at all: '" +
535349cc55cSDimitry Andric                                      Rec->getName() + "'");
536349cc55cSDimitry Andric   return 0;
537349cc55cSDimitry Andric }
538349cc55cSDimitry Andric 
539349cc55cSDimitry Andric static void printPredicates(const std::vector<const Record *> &Predicates,
540349cc55cSDimitry Andric                             StringRef Name, raw_ostream &o) {
541349cc55cSDimitry Andric   for (unsigned i = 0; i < Predicates.size(); ++i) {
542349cc55cSDimitry Andric     StringRef Pred = Predicates[i]->getValueAsString(Name);
543349cc55cSDimitry Andric     o << "  case " << i + 1 << ": {\n"
544349cc55cSDimitry Andric       << "  // " << Predicates[i]->getName() << "\n"
545349cc55cSDimitry Andric       << "  " << Pred << "\n"
546349cc55cSDimitry Andric       << "  }\n";
547349cc55cSDimitry Andric   }
548349cc55cSDimitry Andric }
549349cc55cSDimitry Andric 
550349cc55cSDimitry Andric static void mergeCondAndCode(raw_ostream &CombinedStream, StringRef CondStr,
551349cc55cSDimitry Andric                              StringRef CodeStr) {
552349cc55cSDimitry Andric   // Remove first indentation and last '&&'.
553349cc55cSDimitry Andric   CondStr = CondStr.drop_front(6).drop_back(4);
554349cc55cSDimitry Andric   CombinedStream.indent(4) << "if (" << CondStr << ") {\n";
555349cc55cSDimitry Andric   CombinedStream << CodeStr;
556349cc55cSDimitry Andric   CombinedStream.indent(4) << "  return true;\n";
557349cc55cSDimitry Andric   CombinedStream.indent(4) << "} // if\n";
558349cc55cSDimitry Andric }
559349cc55cSDimitry Andric 
560349cc55cSDimitry Andric void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &o,
561349cc55cSDimitry Andric                                                   EmitterType EType) {
562349cc55cSDimitry Andric   Record *AsmWriter = Target.getAsmWriter();
563349cc55cSDimitry Andric   if (!AsmWriter->getValueAsInt("PassSubtarget"))
564349cc55cSDimitry Andric     PrintFatalError(AsmWriter->getLoc(),
565349cc55cSDimitry Andric                     "'PassSubtarget' is false. SubTargetInfo object is needed "
566349cc55cSDimitry Andric                     "for target features.\n");
567349cc55cSDimitry Andric 
568349cc55cSDimitry Andric   StringRef TargetName = Target.getName();
569349cc55cSDimitry Andric 
570349cc55cSDimitry Andric   // Sort entries in CompressPatterns to handle instructions that can have more
571349cc55cSDimitry Andric   // than one candidate for compression\uncompression, e.g ADD can be
572349cc55cSDimitry Andric   // transformed to a C_ADD or a C_MV. When emitting 'uncompress()' function the
573349cc55cSDimitry Andric   // source and destination are flipped and the sort key needs to change
574349cc55cSDimitry Andric   // accordingly.
575349cc55cSDimitry Andric   llvm::stable_sort(CompressPatterns, [EType](const CompressPat &LHS,
576349cc55cSDimitry Andric                                               const CompressPat &RHS) {
577349cc55cSDimitry Andric     if (EType == EmitterType::Compress || EType == EmitterType::CheckCompress)
578349cc55cSDimitry Andric       return (LHS.Source.TheDef->getName() < RHS.Source.TheDef->getName());
579349cc55cSDimitry Andric     else
580349cc55cSDimitry Andric       return (LHS.Dest.TheDef->getName() < RHS.Dest.TheDef->getName());
581349cc55cSDimitry Andric   });
582349cc55cSDimitry Andric 
583349cc55cSDimitry Andric   // A list of MCOperandPredicates for all operands in use, and the reverse map.
584349cc55cSDimitry Andric   std::vector<const Record *> MCOpPredicates;
585349cc55cSDimitry Andric   DenseMap<const Record *, unsigned> MCOpPredicateMap;
586349cc55cSDimitry Andric   // A list of ImmLeaf Predicates for all operands in use, and the reverse map.
587349cc55cSDimitry Andric   std::vector<const Record *> ImmLeafPredicates;
588349cc55cSDimitry Andric   DenseMap<const Record *, unsigned> ImmLeafPredicateMap;
589349cc55cSDimitry Andric 
590349cc55cSDimitry Andric   std::string F;
591349cc55cSDimitry Andric   std::string FH;
592349cc55cSDimitry Andric   raw_string_ostream Func(F);
593349cc55cSDimitry Andric   raw_string_ostream FuncH(FH);
594349cc55cSDimitry Andric 
595349cc55cSDimitry Andric   if (EType == EmitterType::Compress)
596349cc55cSDimitry Andric     o << "\n#ifdef GEN_COMPRESS_INSTR\n"
597349cc55cSDimitry Andric       << "#undef GEN_COMPRESS_INSTR\n\n";
598349cc55cSDimitry Andric   else if (EType == EmitterType::Uncompress)
599349cc55cSDimitry Andric     o << "\n#ifdef GEN_UNCOMPRESS_INSTR\n"
600349cc55cSDimitry Andric       << "#undef GEN_UNCOMPRESS_INSTR\n\n";
601349cc55cSDimitry Andric   else if (EType == EmitterType::CheckCompress)
602349cc55cSDimitry Andric     o << "\n#ifdef GEN_CHECK_COMPRESS_INSTR\n"
603349cc55cSDimitry Andric       << "#undef GEN_CHECK_COMPRESS_INSTR\n\n";
604349cc55cSDimitry Andric 
605349cc55cSDimitry Andric   if (EType == EmitterType::Compress) {
606349cc55cSDimitry Andric     FuncH << "static bool compressInst(MCInst &OutInst,\n";
607349cc55cSDimitry Andric     FuncH.indent(25) << "const MCInst &MI,\n";
608*bdd1243dSDimitry Andric     FuncH.indent(25) << "const MCSubtargetInfo &STI) {\n";
609349cc55cSDimitry Andric   } else if (EType == EmitterType::Uncompress) {
610349cc55cSDimitry Andric     FuncH << "static bool uncompressInst(MCInst &OutInst,\n";
611349cc55cSDimitry Andric     FuncH.indent(27) << "const MCInst &MI,\n";
612349cc55cSDimitry Andric     FuncH.indent(27) << "const MCSubtargetInfo &STI) {\n";
613349cc55cSDimitry Andric   } else if (EType == EmitterType::CheckCompress) {
614349cc55cSDimitry Andric     FuncH << "static bool isCompressibleInst(const MachineInstr &MI,\n";
615*bdd1243dSDimitry Andric     FuncH.indent(31) << "const " << TargetName << "Subtarget &STI) {\n";
616349cc55cSDimitry Andric   }
617349cc55cSDimitry Andric 
618349cc55cSDimitry Andric   if (CompressPatterns.empty()) {
619349cc55cSDimitry Andric     o << FuncH.str();
620349cc55cSDimitry Andric     o.indent(2) << "return false;\n}\n";
621349cc55cSDimitry Andric     if (EType == EmitterType::Compress)
622349cc55cSDimitry Andric       o << "\n#endif //GEN_COMPRESS_INSTR\n";
623349cc55cSDimitry Andric     else if (EType == EmitterType::Uncompress)
624349cc55cSDimitry Andric       o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
625349cc55cSDimitry Andric     else if (EType == EmitterType::CheckCompress)
626349cc55cSDimitry Andric       o << "\n#endif //GEN_CHECK_COMPRESS_INSTR\n\n";
627349cc55cSDimitry Andric     return;
628349cc55cSDimitry Andric   }
629349cc55cSDimitry Andric 
630349cc55cSDimitry Andric   std::string CaseString;
631349cc55cSDimitry Andric   raw_string_ostream CaseStream(CaseString);
632349cc55cSDimitry Andric   StringRef PrevOp;
633349cc55cSDimitry Andric   StringRef CurOp;
634349cc55cSDimitry Andric   CaseStream << "  switch (MI.getOpcode()) {\n";
635349cc55cSDimitry Andric   CaseStream << "    default: return false;\n";
636349cc55cSDimitry Andric 
637349cc55cSDimitry Andric   bool CompressOrCheck =
638349cc55cSDimitry Andric       EType == EmitterType::Compress || EType == EmitterType::CheckCompress;
639349cc55cSDimitry Andric   bool CompressOrUncompress =
640349cc55cSDimitry Andric       EType == EmitterType::Compress || EType == EmitterType::Uncompress;
641*bdd1243dSDimitry Andric   std::string ValidatorName =
642*bdd1243dSDimitry Andric       CompressOrUncompress
643*bdd1243dSDimitry Andric           ? (TargetName + "ValidateMCOperandFor" +
644*bdd1243dSDimitry Andric              (EType == EmitterType::Compress ? "Compress" : "Uncompress"))
645*bdd1243dSDimitry Andric                 .str()
646*bdd1243dSDimitry Andric           : "";
647349cc55cSDimitry Andric 
648349cc55cSDimitry Andric   for (auto &CompressPat : CompressPatterns) {
649349cc55cSDimitry Andric     if (EType == EmitterType::Uncompress && CompressPat.IsCompressOnly)
650349cc55cSDimitry Andric       continue;
651349cc55cSDimitry Andric 
652349cc55cSDimitry Andric     std::string CondString;
653349cc55cSDimitry Andric     std::string CodeString;
654349cc55cSDimitry Andric     raw_string_ostream CondStream(CondString);
655349cc55cSDimitry Andric     raw_string_ostream CodeStream(CodeString);
656349cc55cSDimitry Andric     CodeGenInstruction &Source =
657349cc55cSDimitry Andric         CompressOrCheck ? CompressPat.Source : CompressPat.Dest;
658349cc55cSDimitry Andric     CodeGenInstruction &Dest =
659349cc55cSDimitry Andric         CompressOrCheck ? CompressPat.Dest : CompressPat.Source;
660349cc55cSDimitry Andric     IndexedMap<OpData> SourceOperandMap = CompressOrCheck
661349cc55cSDimitry Andric                                               ? CompressPat.SourceOperandMap
662349cc55cSDimitry Andric                                               : CompressPat.DestOperandMap;
663349cc55cSDimitry Andric     IndexedMap<OpData> &DestOperandMap = CompressOrCheck
664349cc55cSDimitry Andric                                              ? CompressPat.DestOperandMap
665349cc55cSDimitry Andric                                              : CompressPat.SourceOperandMap;
666349cc55cSDimitry Andric 
667349cc55cSDimitry Andric     CurOp = Source.TheDef->getName();
668349cc55cSDimitry Andric     // Check current and previous opcode to decide to continue or end a case.
669349cc55cSDimitry Andric     if (CurOp != PrevOp) {
670349cc55cSDimitry Andric       if (!PrevOp.empty())
671349cc55cSDimitry Andric         CaseStream.indent(6) << "break;\n    } // case " + PrevOp + "\n";
672349cc55cSDimitry Andric       CaseStream.indent(4) << "case " + TargetName + "::" + CurOp + ": {\n";
673349cc55cSDimitry Andric     }
674349cc55cSDimitry Andric 
675349cc55cSDimitry Andric     std::set<std::pair<bool, StringRef>> FeaturesSet;
676349cc55cSDimitry Andric     std::set<std::set<std::pair<bool, StringRef>>> AnyOfFeatureSets;
677349cc55cSDimitry Andric     // Add CompressPat required features.
678349cc55cSDimitry Andric     getReqFeatures(FeaturesSet, AnyOfFeatureSets, CompressPat.PatReqFeatures);
679349cc55cSDimitry Andric 
680349cc55cSDimitry Andric     // Add Dest instruction required features.
681349cc55cSDimitry Andric     std::vector<Record *> ReqFeatures;
682349cc55cSDimitry Andric     std::vector<Record *> RF = Dest.TheDef->getValueAsListOfDefs("Predicates");
683349cc55cSDimitry Andric     copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
684349cc55cSDimitry Andric       return R->getValueAsBit("AssemblerMatcherPredicate");
685349cc55cSDimitry Andric     });
686349cc55cSDimitry Andric     getReqFeatures(FeaturesSet, AnyOfFeatureSets, ReqFeatures);
687349cc55cSDimitry Andric 
688349cc55cSDimitry Andric     // Emit checks for all required features.
689349cc55cSDimitry Andric     for (auto &Op : FeaturesSet) {
690349cc55cSDimitry Andric       StringRef Not = Op.first ? "!" : "";
691349cc55cSDimitry Andric       CondStream.indent(6) << Not << "STI.getFeatureBits()[" << TargetName
692349cc55cSDimitry Andric                            << "::" << Op.second << "]"
693349cc55cSDimitry Andric                            << " &&\n";
694349cc55cSDimitry Andric     }
695349cc55cSDimitry Andric 
696349cc55cSDimitry Andric     // Emit checks for all required feature groups.
697349cc55cSDimitry Andric     for (auto &Set : AnyOfFeatureSets) {
698349cc55cSDimitry Andric       CondStream.indent(6) << "(";
699349cc55cSDimitry Andric       for (auto &Op : Set) {
700349cc55cSDimitry Andric         bool isLast = &Op == &*Set.rbegin();
701349cc55cSDimitry Andric         StringRef Not = Op.first ? "!" : "";
702349cc55cSDimitry Andric         CondStream << Not << "STI.getFeatureBits()[" << TargetName
703349cc55cSDimitry Andric                    << "::" << Op.second << "]";
704349cc55cSDimitry Andric         if (!isLast)
705349cc55cSDimitry Andric           CondStream << " || ";
706349cc55cSDimitry Andric       }
707349cc55cSDimitry Andric       CondStream << ") &&\n";
708349cc55cSDimitry Andric     }
709349cc55cSDimitry Andric 
710349cc55cSDimitry Andric     // Start Source Inst operands validation.
711349cc55cSDimitry Andric     unsigned OpNo = 0;
712349cc55cSDimitry Andric     for (OpNo = 0; OpNo < Source.Operands.size(); ++OpNo) {
713349cc55cSDimitry Andric       if (SourceOperandMap[OpNo].TiedOpIdx != -1) {
714349cc55cSDimitry Andric         if (Source.Operands[OpNo].Rec->isSubClassOf("RegisterClass"))
715349cc55cSDimitry Andric           CondStream.indent(6)
716*bdd1243dSDimitry Andric               << "(MI.getOperand(" << OpNo << ").isReg()) && (MI.getOperand("
717*bdd1243dSDimitry Andric               << SourceOperandMap[OpNo].TiedOpIdx << ").isReg()) &&\n"
718*bdd1243dSDimitry Andric               << "      (MI.getOperand(" << OpNo
719*bdd1243dSDimitry Andric               << ").getReg() ==  MI.getOperand("
720349cc55cSDimitry Andric               << SourceOperandMap[OpNo].TiedOpIdx << ").getReg()) &&\n";
721349cc55cSDimitry Andric         else
722349cc55cSDimitry Andric           PrintFatalError("Unexpected tied operand types!\n");
723349cc55cSDimitry Andric       }
724349cc55cSDimitry Andric       // Check for fixed immediates\registers in the source instruction.
725349cc55cSDimitry Andric       switch (SourceOperandMap[OpNo].Kind) {
726349cc55cSDimitry Andric       case OpData::Operand:
727349cc55cSDimitry Andric         // We don't need to do anything for source instruction operand checks.
728349cc55cSDimitry Andric         break;
729349cc55cSDimitry Andric       case OpData::Imm:
730349cc55cSDimitry Andric         CondStream.indent(6)
731349cc55cSDimitry Andric             << "(MI.getOperand(" << OpNo << ").isImm()) &&\n"
732349cc55cSDimitry Andric             << "      (MI.getOperand(" << OpNo
733349cc55cSDimitry Andric             << ").getImm() == " << SourceOperandMap[OpNo].Data.Imm << ") &&\n";
734349cc55cSDimitry Andric         break;
735349cc55cSDimitry Andric       case OpData::Reg: {
736349cc55cSDimitry Andric         Record *Reg = SourceOperandMap[OpNo].Data.Reg;
737349cc55cSDimitry Andric         CondStream.indent(6)
738*bdd1243dSDimitry Andric             << "(MI.getOperand(" << OpNo << ").isReg()) &&\n"
739349cc55cSDimitry Andric             << "      (MI.getOperand(" << OpNo << ").getReg() == " << TargetName
740349cc55cSDimitry Andric             << "::" << Reg->getName() << ") &&\n";
741349cc55cSDimitry Andric         break;
742349cc55cSDimitry Andric       }
743349cc55cSDimitry Andric       }
744349cc55cSDimitry Andric     }
745349cc55cSDimitry Andric     CodeStream.indent(6) << "// " << Dest.AsmString << "\n";
746349cc55cSDimitry Andric     if (CompressOrUncompress)
747349cc55cSDimitry Andric       CodeStream.indent(6) << "OutInst.setOpcode(" << TargetName
748349cc55cSDimitry Andric                            << "::" << Dest.TheDef->getName() << ");\n";
749349cc55cSDimitry Andric     OpNo = 0;
750349cc55cSDimitry Andric     for (const auto &DestOperand : Dest.Operands) {
751349cc55cSDimitry Andric       CodeStream.indent(6) << "// Operand: " << DestOperand.Name << "\n";
752349cc55cSDimitry Andric       switch (DestOperandMap[OpNo].Kind) {
753349cc55cSDimitry Andric       case OpData::Operand: {
754349cc55cSDimitry Andric         unsigned OpIdx = DestOperandMap[OpNo].Data.Operand;
755349cc55cSDimitry Andric         // Check that the operand in the Source instruction fits
756349cc55cSDimitry Andric         // the type for the Dest instruction.
757*bdd1243dSDimitry Andric         if (DestOperand.Rec->isSubClassOf("RegisterClass") ||
758*bdd1243dSDimitry Andric             DestOperand.Rec->isSubClassOf("RegisterOperand")) {
759*bdd1243dSDimitry Andric           auto *ClassRec = DestOperand.Rec->isSubClassOf("RegisterClass")
760*bdd1243dSDimitry Andric                                ? DestOperand.Rec
761*bdd1243dSDimitry Andric                                : DestOperand.Rec->getValueAsDef("RegClass");
762349cc55cSDimitry Andric           // This is a register operand. Check the register class.
763349cc55cSDimitry Andric           // Don't check register class if this is a tied operand, it was done
764349cc55cSDimitry Andric           // for the operand its tied to.
765349cc55cSDimitry Andric           if (DestOperand.getTiedRegister() == -1)
766*bdd1243dSDimitry Andric             CondStream.indent(6)
767*bdd1243dSDimitry Andric                 << "(MI.getOperand(" << OpIdx << ").isReg()) &&\n"
768*bdd1243dSDimitry Andric                 << "      (" << TargetName << "MCRegisterClasses["
769*bdd1243dSDimitry Andric                 << TargetName << "::" << ClassRec->getName()
770*bdd1243dSDimitry Andric                 << "RegClassID].contains(MI.getOperand(" << OpIdx
771*bdd1243dSDimitry Andric                 << ").getReg())) &&\n";
772349cc55cSDimitry Andric 
773349cc55cSDimitry Andric           if (CompressOrUncompress)
774349cc55cSDimitry Andric             CodeStream.indent(6)
775349cc55cSDimitry Andric                 << "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";
776349cc55cSDimitry Andric         } else {
777349cc55cSDimitry Andric           // Handling immediate operands.
778349cc55cSDimitry Andric           if (CompressOrUncompress) {
779349cc55cSDimitry Andric             unsigned Entry =
780349cc55cSDimitry Andric                 getPredicates(MCOpPredicateMap, MCOpPredicates, DestOperand.Rec,
781349cc55cSDimitry Andric                               "MCOperandPredicate");
782349cc55cSDimitry Andric             CondStream.indent(6)
783*bdd1243dSDimitry Andric                 << ValidatorName << "("
784349cc55cSDimitry Andric                 << "MI.getOperand(" << OpIdx << "), STI, " << Entry << ") &&\n";
785349cc55cSDimitry Andric           } else {
786349cc55cSDimitry Andric             unsigned Entry =
787349cc55cSDimitry Andric                 getPredicates(ImmLeafPredicateMap, ImmLeafPredicates,
788349cc55cSDimitry Andric                               DestOperand.Rec, "ImmediateCode");
789349cc55cSDimitry Andric             CondStream.indent(6)
790349cc55cSDimitry Andric                 << "MI.getOperand(" << OpIdx << ").isImm() &&\n";
791349cc55cSDimitry Andric             CondStream.indent(6) << TargetName << "ValidateMachineOperand("
792349cc55cSDimitry Andric                                  << "MI.getOperand(" << OpIdx
793*bdd1243dSDimitry Andric                                  << "), &STI, " << Entry << ") &&\n";
794349cc55cSDimitry Andric           }
795349cc55cSDimitry Andric           if (CompressOrUncompress)
796349cc55cSDimitry Andric             CodeStream.indent(6)
797349cc55cSDimitry Andric                 << "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";
798349cc55cSDimitry Andric         }
799349cc55cSDimitry Andric         break;
800349cc55cSDimitry Andric       }
801349cc55cSDimitry Andric       case OpData::Imm: {
802349cc55cSDimitry Andric         if (CompressOrUncompress) {
803349cc55cSDimitry Andric           unsigned Entry = getPredicates(MCOpPredicateMap, MCOpPredicates,
804349cc55cSDimitry Andric                                          DestOperand.Rec, "MCOperandPredicate");
805349cc55cSDimitry Andric           CondStream.indent(6)
806*bdd1243dSDimitry Andric               << ValidatorName << "("
807349cc55cSDimitry Andric               << "MCOperand::createImm(" << DestOperandMap[OpNo].Data.Imm
808349cc55cSDimitry Andric               << "), STI, " << Entry << ") &&\n";
809349cc55cSDimitry Andric         } else {
810349cc55cSDimitry Andric           unsigned Entry = getPredicates(ImmLeafPredicateMap, ImmLeafPredicates,
811349cc55cSDimitry Andric                                          DestOperand.Rec, "ImmediateCode");
812349cc55cSDimitry Andric           CondStream.indent(6)
813349cc55cSDimitry Andric               << TargetName
814349cc55cSDimitry Andric               << "ValidateMachineOperand(MachineOperand::CreateImm("
815*bdd1243dSDimitry Andric               << DestOperandMap[OpNo].Data.Imm << "), &STI, " << Entry
816349cc55cSDimitry Andric               << ") &&\n";
817349cc55cSDimitry Andric         }
818349cc55cSDimitry Andric         if (CompressOrUncompress)
819349cc55cSDimitry Andric           CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createImm("
820349cc55cSDimitry Andric                                << DestOperandMap[OpNo].Data.Imm << "));\n";
821349cc55cSDimitry Andric       } break;
822349cc55cSDimitry Andric       case OpData::Reg: {
823349cc55cSDimitry Andric         if (CompressOrUncompress) {
824349cc55cSDimitry Andric           // Fixed register has been validated at pattern validation time.
825349cc55cSDimitry Andric           Record *Reg = DestOperandMap[OpNo].Data.Reg;
826349cc55cSDimitry Andric           CodeStream.indent(6)
827349cc55cSDimitry Andric               << "OutInst.addOperand(MCOperand::createReg(" << TargetName
828349cc55cSDimitry Andric               << "::" << Reg->getName() << "));\n";
829349cc55cSDimitry Andric         }
830349cc55cSDimitry Andric       } break;
831349cc55cSDimitry Andric       }
832349cc55cSDimitry Andric       ++OpNo;
833349cc55cSDimitry Andric     }
834349cc55cSDimitry Andric     if (CompressOrUncompress)
835349cc55cSDimitry Andric       CodeStream.indent(6) << "OutInst.setLoc(MI.getLoc());\n";
836349cc55cSDimitry Andric     mergeCondAndCode(CaseStream, CondStream.str(), CodeStream.str());
837349cc55cSDimitry Andric     PrevOp = CurOp;
838349cc55cSDimitry Andric   }
839349cc55cSDimitry Andric   Func << CaseStream.str() << "\n";
840349cc55cSDimitry Andric   // Close brace for the last case.
841349cc55cSDimitry Andric   Func.indent(4) << "} // case " << CurOp << "\n";
842349cc55cSDimitry Andric   Func.indent(2) << "} // switch\n";
843349cc55cSDimitry Andric   Func.indent(2) << "return false;\n}\n";
844349cc55cSDimitry Andric 
845349cc55cSDimitry Andric   if (!MCOpPredicates.empty()) {
846*bdd1243dSDimitry Andric     o << "static bool " << ValidatorName << "(const MCOperand &MCOp,\n"
847349cc55cSDimitry Andric       << "                  const MCSubtargetInfo &STI,\n"
848349cc55cSDimitry Andric       << "                  unsigned PredicateIndex) {\n"
849349cc55cSDimitry Andric       << "  switch (PredicateIndex) {\n"
850349cc55cSDimitry Andric       << "  default:\n"
851349cc55cSDimitry Andric       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
852349cc55cSDimitry Andric       << "    break;\n";
853349cc55cSDimitry Andric 
854349cc55cSDimitry Andric     printPredicates(MCOpPredicates, "MCOperandPredicate", o);
855349cc55cSDimitry Andric 
856349cc55cSDimitry Andric     o << "  }\n"
857349cc55cSDimitry Andric       << "}\n\n";
858349cc55cSDimitry Andric   }
859349cc55cSDimitry Andric 
860349cc55cSDimitry Andric   if (!ImmLeafPredicates.empty()) {
861349cc55cSDimitry Andric     o << "static bool " << TargetName
862349cc55cSDimitry Andric       << "ValidateMachineOperand(const MachineOperand &MO,\n"
863349cc55cSDimitry Andric       << "                  const " << TargetName << "Subtarget *Subtarget,\n"
864349cc55cSDimitry Andric       << "                  unsigned PredicateIndex) {\n"
865349cc55cSDimitry Andric       << "  int64_t Imm = MO.getImm();\n"
866349cc55cSDimitry Andric       << "  switch (PredicateIndex) {\n"
867349cc55cSDimitry Andric       << "  default:\n"
868349cc55cSDimitry Andric       << "    llvm_unreachable(\"Unknown ImmLeaf Predicate kind\");\n"
869349cc55cSDimitry Andric       << "    break;\n";
870349cc55cSDimitry Andric 
871349cc55cSDimitry Andric     printPredicates(ImmLeafPredicates, "ImmediateCode", o);
872349cc55cSDimitry Andric 
873349cc55cSDimitry Andric     o << "  }\n"
874349cc55cSDimitry Andric       << "}\n\n";
875349cc55cSDimitry Andric   }
876349cc55cSDimitry Andric 
877349cc55cSDimitry Andric   o << FuncH.str();
878349cc55cSDimitry Andric   o << Func.str();
879349cc55cSDimitry Andric 
880349cc55cSDimitry Andric   if (EType == EmitterType::Compress)
881349cc55cSDimitry Andric     o << "\n#endif //GEN_COMPRESS_INSTR\n";
882349cc55cSDimitry Andric   else if (EType == EmitterType::Uncompress)
883349cc55cSDimitry Andric     o << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";
884349cc55cSDimitry Andric   else if (EType == EmitterType::CheckCompress)
885349cc55cSDimitry Andric     o << "\n#endif //GEN_CHECK_COMPRESS_INSTR\n\n";
886349cc55cSDimitry Andric }
887349cc55cSDimitry Andric 
888349cc55cSDimitry Andric void CompressInstEmitter::run(raw_ostream &o) {
889349cc55cSDimitry Andric   std::vector<Record *> Insts = Records.getAllDerivedDefinitions("CompressPat");
890349cc55cSDimitry Andric 
891349cc55cSDimitry Andric   // Process the CompressPat definitions, validating them as we do so.
892349cc55cSDimitry Andric   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
893349cc55cSDimitry Andric     evaluateCompressPat(Insts[i]);
894349cc55cSDimitry Andric 
895349cc55cSDimitry Andric   // Emit file header.
896349cc55cSDimitry Andric   emitSourceFileHeader("Compress instruction Source Fragment", o);
897349cc55cSDimitry Andric   // Generate compressInst() function.
898349cc55cSDimitry Andric   emitCompressInstEmitter(o, EmitterType::Compress);
899349cc55cSDimitry Andric   // Generate uncompressInst() function.
900349cc55cSDimitry Andric   emitCompressInstEmitter(o, EmitterType::Uncompress);
901349cc55cSDimitry Andric   // Generate isCompressibleInst() function.
902349cc55cSDimitry Andric   emitCompressInstEmitter(o, EmitterType::CheckCompress);
903349cc55cSDimitry Andric }
904349cc55cSDimitry Andric 
905349cc55cSDimitry Andric namespace llvm {
906349cc55cSDimitry Andric 
907349cc55cSDimitry Andric void EmitCompressInst(RecordKeeper &RK, raw_ostream &OS) {
908349cc55cSDimitry Andric   CompressInstEmitter(RK).run(OS);
909349cc55cSDimitry Andric }
910349cc55cSDimitry Andric 
911349cc55cSDimitry Andric } // namespace llvm
912