[AVX] Make Inits Foldable
[oota-llvm.git] / utils / TableGen / CodeGenInstruction.cpp
1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the CodeGenInstruction class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
16 #include "Error.h"
17 #include "Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include <set>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // CGIOperandList Implementation
26 //===----------------------------------------------------------------------===//
27
28 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
29   isPredicable = false;
30   hasOptionalDef = false;
31   isVariadic = false;
32
33   const DagInit *OutDI = R->getValueAsDag("OutOperandList");
34
35   if (const DefInit *Init =
36       dynamic_cast<const DefInit*>(OutDI->getOperator())) {
37     if (Init->getDef()->getName() != "outs")
38       throw R->getName() + ": invalid def name for output list: use 'outs'";
39   } else
40     throw R->getName() + ": invalid output list: use 'outs'";
41
42   NumDefs = OutDI->getNumArgs();
43
44   const DagInit *InDI = R->getValueAsDag("InOperandList");
45   if (const DefInit *Init = dynamic_cast<const DefInit*>(InDI->getOperator())) {
46     if (Init->getDef()->getName() != "ins")
47       throw R->getName() + ": invalid def name for input list: use 'ins'";
48   } else
49     throw R->getName() + ": invalid input list: use 'ins'";
50
51   unsigned MIOperandNo = 0;
52   std::set<std::string> OperandNames;
53   for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
54     const Init *ArgInit;
55     std::string ArgName;
56     if (i < NumDefs) {
57       ArgInit = OutDI->getArg(i);
58       ArgName = OutDI->getArgName(i);
59     } else {
60       ArgInit = InDI->getArg(i-NumDefs);
61       ArgName = InDI->getArgName(i-NumDefs);
62     }
63
64     const DefInit *Arg = dynamic_cast<const DefInit*>(ArgInit);
65     if (!Arg)
66       throw "Illegal operand for the '" + R->getName() + "' instruction!";
67
68     Record *Rec = Arg->getDef();
69     std::string PrintMethod = "printOperand";
70     std::string EncoderMethod;
71     unsigned NumOps = 1;
72     const DagInit *MIOpInfo = 0;
73     if (Rec->isSubClassOf("RegisterOperand")) {
74       PrintMethod = Rec->getValueAsString("PrintMethod");
75     } else if (Rec->isSubClassOf("Operand")) {
76       PrintMethod = Rec->getValueAsString("PrintMethod");
77       // If there is an explicit encoder method, use it.
78       EncoderMethod = Rec->getValueAsString("EncoderMethod");
79       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
80
81       // Verify that MIOpInfo has an 'ops' root value.
82       if (!dynamic_cast<const DefInit*>(MIOpInfo->getOperator()) ||
83           dynamic_cast<const DefInit*>(MIOpInfo->getOperator())
84           ->getDef()->getName() != "ops")
85         throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
86         "'\n";
87
88       // If we have MIOpInfo, then we have #operands equal to number of entries
89       // in MIOperandInfo.
90       if (unsigned NumArgs = MIOpInfo->getNumArgs())
91         NumOps = NumArgs;
92
93       if (Rec->isSubClassOf("PredicateOperand"))
94         isPredicable = true;
95       else if (Rec->isSubClassOf("OptionalDefOperand"))
96         hasOptionalDef = true;
97     } else if (Rec->getName() == "variable_ops") {
98       isVariadic = true;
99       continue;
100     } else if (!Rec->isSubClassOf("RegisterClass") &&
101                !Rec->isSubClassOf("PointerLikeRegClass") &&
102                Rec->getName() != "unknown")
103       throw "Unknown operand class '" + Rec->getName() +
104       "' in '" + R->getName() + "' instruction!";
105
106     // Check that the operand has a name and that it's unique.
107     if (ArgName.empty())
108       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
109       " has no name!";
110     if (!OperandNames.insert(ArgName).second)
111       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
112       " has the same name as a previous operand!";
113
114     OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
115                                       MIOperandNo, NumOps, MIOpInfo));
116     MIOperandNo += NumOps;
117   }
118
119
120   // Make sure the constraints list for each operand is large enough to hold
121   // constraint info, even if none is present.
122   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
123     OperandList[i].Constraints.resize(OperandList[i].MINumOperands);
124 }
125
126
127 /// getOperandNamed - Return the index of the operand with the specified
128 /// non-empty name.  If the instruction does not have an operand with the
129 /// specified name, throw an exception.
130 ///
131 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
132   unsigned OpIdx;
133   if (hasOperandNamed(Name, OpIdx)) return OpIdx;
134   throw "'" + TheDef->getName() + "' does not have an operand named '$" +
135     Name.str() + "'!";
136 }
137
138 /// hasOperandNamed - Query whether the instruction has an operand of the
139 /// given name. If so, return true and set OpIdx to the index of the
140 /// operand. Otherwise, return false.
141 bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
142   assert(!Name.empty() && "Cannot search for operand with no name!");
143   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
144     if (OperandList[i].Name == Name) {
145       OpIdx = i;
146       return true;
147     }
148   return false;
149 }
150
151 std::pair<unsigned,unsigned>
152 CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
153   if (Op.empty() || Op[0] != '$')
154     throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
155
156   std::string OpName = Op.substr(1);
157   std::string SubOpName;
158
159   // Check to see if this is $foo.bar.
160   std::string::size_type DotIdx = OpName.find_first_of(".");
161   if (DotIdx != std::string::npos) {
162     SubOpName = OpName.substr(DotIdx+1);
163     if (SubOpName.empty())
164       throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
165     OpName = OpName.substr(0, DotIdx);
166   }
167
168   unsigned OpIdx = getOperandNamed(OpName);
169
170   if (SubOpName.empty()) {  // If no suboperand name was specified:
171     // If one was needed, throw.
172     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
173         SubOpName.empty())
174       throw TheDef->getName() + ": Illegal to refer to"
175       " whole operand part of complex operand '" + Op + "'";
176
177     // Otherwise, return the operand.
178     return std::make_pair(OpIdx, 0U);
179   }
180
181   // Find the suboperand number involved.
182   const DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
183   if (MIOpInfo == 0)
184     throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
185
186   // Find the operand with the right name.
187   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
188     if (MIOpInfo->getArgName(i) == SubOpName)
189       return std::make_pair(OpIdx, i);
190
191   // Otherwise, didn't find it!
192   throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
193 }
194
195 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops) {
196   // EARLY_CLOBBER: @early $reg
197   std::string::size_type wpos = CStr.find_first_of(" \t");
198   std::string::size_type start = CStr.find_first_not_of(" \t");
199   std::string Tok = CStr.substr(start, wpos - start);
200   if (Tok == "@earlyclobber") {
201     std::string Name = CStr.substr(wpos+1);
202     wpos = Name.find_first_not_of(" \t");
203     if (wpos == std::string::npos)
204       throw "Illegal format for @earlyclobber constraint: '" + CStr + "'";
205     Name = Name.substr(wpos);
206     std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
207
208     // Build the string for the operand
209     if (!Ops[Op.first].Constraints[Op.second].isNone())
210       throw "Operand '" + Name + "' cannot have multiple constraints!";
211     Ops[Op.first].Constraints[Op.second] =
212     CGIOperandList::ConstraintInfo::getEarlyClobber();
213     return;
214   }
215
216   // Only other constraint is "TIED_TO" for now.
217   std::string::size_type pos = CStr.find_first_of('=');
218   assert(pos != std::string::npos && "Unrecognized constraint");
219   start = CStr.find_first_not_of(" \t");
220   std::string Name = CStr.substr(start, pos - start);
221
222   // TIED_TO: $src1 = $dst
223   wpos = Name.find_first_of(" \t");
224   if (wpos == std::string::npos)
225     throw "Illegal format for tied-to constraint: '" + CStr + "'";
226   std::string DestOpName = Name.substr(0, wpos);
227   std::pair<unsigned,unsigned> DestOp = Ops.ParseOperandName(DestOpName, false);
228
229   Name = CStr.substr(pos+1);
230   wpos = Name.find_first_not_of(" \t");
231   if (wpos == std::string::npos)
232     throw "Illegal format for tied-to constraint: '" + CStr + "'";
233
234   std::pair<unsigned,unsigned> SrcOp =
235   Ops.ParseOperandName(Name.substr(wpos), false);
236   if (SrcOp > DestOp)
237     throw "Illegal tied-to operand constraint '" + CStr + "'";
238
239
240   unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
241
242   if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
243     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
244   Ops[DestOp.first].Constraints[DestOp.second] =
245   CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
246 }
247
248 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
249   if (CStr.empty()) return;
250
251   const std::string delims(",");
252   std::string::size_type bidx, eidx;
253
254   bidx = CStr.find_first_not_of(delims);
255   while (bidx != std::string::npos) {
256     eidx = CStr.find_first_of(delims, bidx);
257     if (eidx == std::string::npos)
258       eidx = CStr.length();
259
260     ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
261     bidx = CStr.find_first_not_of(delims, eidx);
262   }
263 }
264
265 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
266   while (1) {
267     std::string OpName;
268     tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
269     if (OpName.empty()) break;
270
271     // Figure out which operand this is.
272     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
273
274     // Mark the operand as not-to-be encoded.
275     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
276       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
277     OperandList[Op.first].DoNotEncode[Op.second] = true;
278   }
279
280 }
281
282 //===----------------------------------------------------------------------===//
283 // CodeGenInstruction Implementation
284 //===----------------------------------------------------------------------===//
285
286 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
287   Namespace = R->getValueAsString("Namespace");
288   AsmString = R->getValueAsString("AsmString");
289
290   isReturn     = R->getValueAsBit("isReturn");
291   isBranch     = R->getValueAsBit("isBranch");
292   isIndirectBranch = R->getValueAsBit("isIndirectBranch");
293   isCompare    = R->getValueAsBit("isCompare");
294   isMoveImm    = R->getValueAsBit("isMoveImm");
295   isBitcast    = R->getValueAsBit("isBitcast");
296   isBarrier    = R->getValueAsBit("isBarrier");
297   isCall       = R->getValueAsBit("isCall");
298   canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
299   mayLoad      = R->getValueAsBit("mayLoad");
300   mayStore     = R->getValueAsBit("mayStore");
301   isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
302   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
303   isCommutable = R->getValueAsBit("isCommutable");
304   isTerminator = R->getValueAsBit("isTerminator");
305   isReMaterializable = R->getValueAsBit("isReMaterializable");
306   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
307   usesCustomInserter = R->getValueAsBit("usesCustomInserter");
308   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
309   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
310   hasSideEffects = R->getValueAsBit("hasSideEffects");
311   neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
312   isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
313   hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
314   hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
315   isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
316   isPseudo = R->getValueAsBit("isPseudo");
317   ImplicitDefs = R->getValueAsListOfDefs("Defs");
318   ImplicitUses = R->getValueAsListOfDefs("Uses");
319
320   if (neverHasSideEffects + hasSideEffects > 1)
321     throw R->getName() + ": multiple conflicting side-effect flags set!";
322
323   // Parse Constraints.
324   ParseConstraints(R->getValueAsString("Constraints"), Operands);
325
326   // Parse the DisableEncoding field.
327   Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
328 }
329
330 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
331 /// implicit def and it has a known VT, return the VT, otherwise return
332 /// MVT::Other.
333 MVT::SimpleValueType CodeGenInstruction::
334 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
335   if (ImplicitDefs.empty()) return MVT::Other;
336
337   // Check to see if the first implicit def has a resolvable type.
338   Record *FirstImplicitDef = ImplicitDefs[0];
339   assert(FirstImplicitDef->isSubClassOf("Register"));
340   const std::vector<MVT::SimpleValueType> &RegVTs =
341     TargetInfo.getRegisterVTs(FirstImplicitDef);
342   if (RegVTs.size() == 1)
343     return RegVTs[0];
344   return MVT::Other;
345 }
346
347
348 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
349 /// include text from the specified variant, returning the new string.
350 std::string CodeGenInstruction::
351 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
352   std::string Res = "";
353
354   for (;;) {
355     // Find the start of the next variant string.
356     size_t VariantsStart = 0;
357     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
358       if (Cur[VariantsStart] == '{' &&
359           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
360                                   Cur[VariantsStart-1] != '\\')))
361         break;
362
363     // Add the prefix to the result.
364     Res += Cur.slice(0, VariantsStart);
365     if (VariantsStart == Cur.size())
366       break;
367
368     ++VariantsStart; // Skip the '{'.
369
370     // Scan to the end of the variants string.
371     size_t VariantsEnd = VariantsStart;
372     unsigned NestedBraces = 1;
373     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
374       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
375         if (--NestedBraces == 0)
376           break;
377       } else if (Cur[VariantsEnd] == '{')
378         ++NestedBraces;
379     }
380
381     // Select the Nth variant (or empty).
382     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
383     for (unsigned i = 0; i != Variant; ++i)
384       Selection = Selection.split('|').second;
385     Res += Selection.split('|').first;
386
387     assert(VariantsEnd != Cur.size() &&
388            "Unterminated variants in assembly string!");
389     Cur = Cur.substr(VariantsEnd + 1);
390   }
391
392   return Res;
393 }
394
395
396 //===----------------------------------------------------------------------===//
397 /// CodeGenInstAlias Implementation
398 //===----------------------------------------------------------------------===//
399
400 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
401 /// constructor.  It checks if an argument in an InstAlias pattern matches
402 /// the corresponding operand of the instruction.  It returns true on a
403 /// successful match, with ResOp set to the result operand to be used.
404 bool CodeGenInstAlias::tryAliasOpMatch(const DagInit *Result,
405                                        unsigned AliasOpNo,
406                                        Record *InstOpRec, bool hasSubOps,
407                                        SMLoc Loc, CodeGenTarget &T,
408                                        ResultOperand &ResOp) {
409   const Init *Arg = Result->getArg(AliasOpNo);
410   const DefInit *ADI = dynamic_cast<const DefInit*>(Arg);
411
412   if (ADI && ADI->getDef() == InstOpRec) {
413     // If the operand is a record, it must have a name, and the record type
414     // must match up with the instruction's argument type.
415     if (Result->getArgName(AliasOpNo).empty())
416       throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
417                     " must have a name!");
418     ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
419     return true;
420   }
421
422   // Handle explicit registers.
423   if (ADI && ADI->getDef()->isSubClassOf("Register")) {
424     if (InstOpRec->isSubClassOf("RegisterOperand"))
425       InstOpRec = InstOpRec->getValueAsDef("RegClass");
426
427     if (!InstOpRec->isSubClassOf("RegisterClass"))
428       return false;
429
430     if (!T.getRegisterClass(InstOpRec)
431         .contains(T.getRegBank().getReg(ADI->getDef())))
432       throw TGError(Loc, "fixed register " +ADI->getDef()->getName()
433                     + " is not a member of the " + InstOpRec->getName() +
434                     " register class!");
435
436     if (!Result->getArgName(AliasOpNo).empty())
437       throw TGError(Loc, "result fixed register argument must "
438                     "not have a name!");
439
440     ResOp = ResultOperand(ADI->getDef());
441     return true;
442   }
443
444   // Handle "zero_reg" for optional def operands.
445   if (ADI && ADI->getDef()->getName() == "zero_reg") {
446
447     // Check if this is an optional def.
448     if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
449       throw TGError(Loc, "reg0 used for result that is not an "
450                     "OptionalDefOperand!");
451
452     ResOp = ResultOperand(static_cast<Record*>(0));
453     return true;
454   }
455
456   if (const IntInit *II = dynamic_cast<const IntInit*>(Arg)) {
457     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
458       return false;
459     // Integer arguments can't have names.
460     if (!Result->getArgName(AliasOpNo).empty())
461       throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
462                     " must not have a name!");
463     ResOp = ResultOperand(II->getValue());
464     return true;
465   }
466
467   return false;
468 }
469
470 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
471   AsmString = R->getValueAsString("AsmString");
472   Result = R->getValueAsDag("ResultInst");
473
474   // Verify that the root of the result is an instruction.
475   const DefInit *DI = dynamic_cast<const DefInit*>(Result->getOperator());
476   if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
477     throw TGError(R->getLoc(), "result of inst alias should be an instruction");
478
479   ResultInst = &T.getInstruction(DI->getDef());
480
481   // NameClass - If argument names are repeated, we need to verify they have
482   // the same class.
483   StringMap<Record*> NameClass;
484   for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
485     const DefInit *ADI = dynamic_cast<const DefInit*>(Result->getArg(i));
486     if (!ADI || Result->getArgName(i).empty())
487       continue;
488     // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
489     // $foo can exist multiple times in the result list, but it must have the
490     // same type.
491     Record *&Entry = NameClass[Result->getArgName(i)];
492     if (Entry && Entry != ADI->getDef())
493       throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
494                     " is both " + Entry->getName() + " and " +
495                     ADI->getDef()->getName() + "!");
496     Entry = ADI->getDef();
497   }
498
499   // Decode and validate the arguments of the result.
500   unsigned AliasOpNo = 0;
501   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
502
503     // Tied registers don't have an entry in the result dag.
504     if (ResultInst->Operands[i].getTiedRegister() != -1)
505       continue;
506
507     if (AliasOpNo >= Result->getNumArgs())
508       throw TGError(R->getLoc(), "not enough arguments for instruction!");
509
510     Record *InstOpRec = ResultInst->Operands[i].Rec;
511     unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
512     ResultOperand ResOp(static_cast<int64_t>(0));
513     if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
514                         R->getLoc(), T, ResOp)) {
515       ResultOperands.push_back(ResOp);
516       ResultInstOperandIndex.push_back(std::make_pair(i, -1));
517       ++AliasOpNo;
518       continue;
519     }
520
521     // If the argument did not match the instruction operand, and the operand
522     // is composed of multiple suboperands, try matching the suboperands.
523     if (NumSubOps > 1) {
524       const DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
525       for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
526         if (AliasOpNo >= Result->getNumArgs())
527           throw TGError(R->getLoc(), "not enough arguments for instruction!");
528         Record *SubRec =
529           dynamic_cast<const DefInit*>(MIOI->getArg(SubOp))->getDef();
530         if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
531                             R->getLoc(), T, ResOp)) {
532           ResultOperands.push_back(ResOp);
533           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
534           ++AliasOpNo;
535         } else {
536           throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
537                         " does not match instruction operand class " +
538                         (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
539         }
540       }
541       continue;
542     }
543     throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
544                   " does not match instruction operand class " +
545                   InstOpRec->getName());
546   }
547
548   if (AliasOpNo != Result->getNumArgs())
549     throw TGError(R->getLoc(), "too many operands for instruction!");
550 }