1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenInstruction class.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
24 //===----------------------------------------------------------------------===//
25 // CGIOperandList Implementation
26 //===----------------------------------------------------------------------===//
28 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
30 hasOptionalDef = false;
33 const DagInit *OutDI = R->getValueAsDag("OutOperandList");
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'";
40 throw R->getName() + ": invalid output list: use 'outs'";
42 NumDefs = OutDI->getNumArgs();
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'";
49 throw R->getName() + ": invalid input list: use 'ins'";
51 unsigned MIOperandNo = 0;
52 std::set<std::string> OperandNames;
53 for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
57 ArgInit = OutDI->getArg(i);
58 ArgName = OutDI->getArgName(i);
60 ArgInit = InDI->getArg(i-NumDefs);
61 ArgName = InDI->getArgName(i-NumDefs);
64 const DefInit *Arg = dynamic_cast<const DefInit*>(ArgInit);
66 throw "Illegal operand for the '" + R->getName() + "' instruction!";
68 Record *Rec = Arg->getDef();
69 std::string PrintMethod = "printOperand";
70 std::string EncoderMethod;
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");
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() +
88 // If we have MIOpInfo, then we have #operands equal to number of entries
90 if (unsigned NumArgs = MIOpInfo->getNumArgs())
93 if (Rec->isSubClassOf("PredicateOperand"))
95 else if (Rec->isSubClassOf("OptionalDefOperand"))
96 hasOptionalDef = true;
97 } else if (Rec->getName() == "variable_ops") {
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!";
106 // Check that the operand has a name and that it's unique.
108 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
110 if (!OperandNames.insert(ArgName).second)
111 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
112 " has the same name as a previous operand!";
114 OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
115 MIOperandNo, NumOps, MIOpInfo));
116 MIOperandNo += NumOps;
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);
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.
131 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
133 if (hasOperandNamed(Name, OpIdx)) return OpIdx;
134 throw "'" + TheDef->getName() + "' does not have an operand named '$" +
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) {
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 + "'";
156 std::string OpName = Op.substr(1);
157 std::string SubOpName;
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);
168 unsigned OpIdx = getOperandNamed(OpName);
170 if (SubOpName.empty()) { // If no suboperand name was specified:
171 // If one was needed, throw.
172 if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
174 throw TheDef->getName() + ": Illegal to refer to"
175 " whole operand part of complex operand '" + Op + "'";
177 // Otherwise, return the operand.
178 return std::make_pair(OpIdx, 0U);
181 // Find the suboperand number involved.
182 const DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
184 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
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);
191 // Otherwise, didn't find it!
192 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
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);
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();
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);
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);
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 + "'";
234 std::pair<unsigned,unsigned> SrcOp =
235 Ops.ParseOperandName(Name.substr(wpos), false);
237 throw "Illegal tied-to operand constraint '" + CStr + "'";
240 unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
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);
248 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
249 if (CStr.empty()) return;
251 const std::string delims(",");
252 std::string::size_type bidx, eidx;
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();
260 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
261 bidx = CStr.find_first_not_of(delims, eidx);
265 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
268 tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
269 if (OpName.empty()) break;
271 // Figure out which operand this is.
272 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
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;
282 //===----------------------------------------------------------------------===//
283 // CodeGenInstruction Implementation
284 //===----------------------------------------------------------------------===//
286 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
287 Namespace = R->getValueAsString("Namespace");
288 AsmString = R->getValueAsString("AsmString");
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");
320 if (neverHasSideEffects + hasSideEffects > 1)
321 throw R->getName() + ": multiple conflicting side-effect flags set!";
323 // Parse Constraints.
324 ParseConstraints(R->getValueAsString("Constraints"), Operands);
326 // Parse the DisableEncoding field.
327 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
330 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
331 /// implicit def and it has a known VT, return the VT, otherwise return
333 MVT::SimpleValueType CodeGenInstruction::
334 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
335 if (ImplicitDefs.empty()) return MVT::Other;
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)
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 = "";
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] != '\\')))
363 // Add the prefix to the result.
364 Res += Cur.slice(0, VariantsStart);
365 if (VariantsStart == Cur.size())
368 ++VariantsStart; // Skip the '{'.
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)
377 } else if (Cur[VariantsEnd] == '{')
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;
387 assert(VariantsEnd != Cur.size() &&
388 "Unterminated variants in assembly string!");
389 Cur = Cur.substr(VariantsEnd + 1);
396 //===----------------------------------------------------------------------===//
397 /// CodeGenInstAlias Implementation
398 //===----------------------------------------------------------------------===//
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,
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);
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());
422 // Handle explicit registers.
423 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
424 if (InstOpRec->isSubClassOf("RegisterOperand"))
425 InstOpRec = InstOpRec->getValueAsDef("RegClass");
427 if (!InstOpRec->isSubClassOf("RegisterClass"))
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() +
436 if (!Result->getArgName(AliasOpNo).empty())
437 throw TGError(Loc, "result fixed register argument must "
440 ResOp = ResultOperand(ADI->getDef());
444 // Handle "zero_reg" for optional def operands.
445 if (ADI && ADI->getDef()->getName() == "zero_reg") {
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!");
452 ResOp = ResultOperand(static_cast<Record*>(0));
456 if (const IntInit *II = dynamic_cast<const IntInit*>(Arg)) {
457 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
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());
470 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
471 AsmString = R->getValueAsString("AsmString");
472 Result = R->getValueAsDag("ResultInst");
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");
479 ResultInst = &T.getInstruction(DI->getDef());
481 // NameClass - If argument names are repeated, we need to verify they have
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())
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
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();
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) {
503 // Tied registers don't have an entry in the result dag.
504 if (ResultInst->Operands[i].getTiedRegister() != -1)
507 if (AliasOpNo >= Result->getNumArgs())
508 throw TGError(R->getLoc(), "not enough arguments for instruction!");
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));
521 // If the argument did not match the instruction operand, and the operand
522 // is composed of multiple suboperands, try matching the suboperands.
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!");
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));
536 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
537 " does not match instruction operand class " +
538 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
543 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
544 " does not match instruction operand class " +
545 InstOpRec->getName());
548 if (AliasOpNo != Result->getNumArgs())
549 throw TGError(R->getLoc(), "too many operands for instruction!");