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 DagInit *OutDI = R->getValueAsDag("OutOperandList");
35 if (DefInit *Init = dynamic_cast<DefInit*>(OutDI->getOperator())) {
36 if (Init->getDef()->getName() != "outs")
37 throw R->getName() + ": invalid def name for output list: use 'outs'";
39 throw R->getName() + ": invalid output list: use 'outs'";
41 NumDefs = OutDI->getNumArgs();
43 DagInit *InDI = R->getValueAsDag("InOperandList");
44 if (DefInit *Init = dynamic_cast<DefInit*>(InDI->getOperator())) {
45 if (Init->getDef()->getName() != "ins")
46 throw R->getName() + ": invalid def name for input list: use 'ins'";
48 throw R->getName() + ": invalid input list: use 'ins'";
50 unsigned MIOperandNo = 0;
51 std::set<std::string> OperandNames;
52 for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
56 ArgInit = OutDI->getArg(i);
57 ArgName = OutDI->getArgName(i);
59 ArgInit = InDI->getArg(i-NumDefs);
60 ArgName = InDI->getArgName(i-NumDefs);
63 DefInit *Arg = dynamic_cast<DefInit*>(ArgInit);
65 throw "Illegal operand for the '" + R->getName() + "' instruction!";
67 Record *Rec = Arg->getDef();
68 std::string PrintMethod = "printOperand";
69 std::string EncoderMethod;
71 DagInit *MIOpInfo = 0;
72 if (Rec->isSubClassOf("Operand")) {
73 PrintMethod = Rec->getValueAsString("PrintMethod");
74 // If there is an explicit encoder method, use it.
75 EncoderMethod = Rec->getValueAsString("EncoderMethod");
76 MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
78 // Verify that MIOpInfo has an 'ops' root value.
79 if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
80 dynamic_cast<DefInit*>(MIOpInfo->getOperator())
81 ->getDef()->getName() != "ops")
82 throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
85 // If we have MIOpInfo, then we have #operands equal to number of entries
87 if (unsigned NumArgs = MIOpInfo->getNumArgs())
90 if (Rec->isSubClassOf("PredicateOperand"))
92 else if (Rec->isSubClassOf("OptionalDefOperand"))
93 hasOptionalDef = true;
94 } else if (Rec->getName() == "variable_ops") {
97 } else if (!Rec->isSubClassOf("RegisterClass") &&
98 !Rec->isSubClassOf("PointerLikeRegClass") &&
99 Rec->getName() != "unknown")
100 throw "Unknown operand class '" + Rec->getName() +
101 "' in '" + R->getName() + "' instruction!";
103 // Check that the operand has a name and that it's unique.
105 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
107 if (!OperandNames.insert(ArgName).second)
108 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
109 " has the same name as a previous operand!";
111 OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
112 MIOperandNo, NumOps, MIOpInfo));
113 MIOperandNo += NumOps;
117 // Make sure the constraints list for each operand is large enough to hold
118 // constraint info, even if none is present.
119 for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
120 OperandList[i].Constraints.resize(OperandList[i].MINumOperands);
124 /// getOperandNamed - Return the index of the operand with the specified
125 /// non-empty name. If the instruction does not have an operand with the
126 /// specified name, throw an exception.
128 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
130 if (hasOperandNamed(Name, OpIdx)) return OpIdx;
131 throw "'" + TheDef->getName() + "' does not have an operand named '$" +
135 /// hasOperandNamed - Query whether the instruction has an operand of the
136 /// given name. If so, return true and set OpIdx to the index of the
137 /// operand. Otherwise, return false.
138 bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
139 assert(!Name.empty() && "Cannot search for operand with no name!");
140 for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
141 if (OperandList[i].Name == Name) {
148 std::pair<unsigned,unsigned>
149 CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
150 if (Op.empty() || Op[0] != '$')
151 throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
153 std::string OpName = Op.substr(1);
154 std::string SubOpName;
156 // Check to see if this is $foo.bar.
157 std::string::size_type DotIdx = OpName.find_first_of(".");
158 if (DotIdx != std::string::npos) {
159 SubOpName = OpName.substr(DotIdx+1);
160 if (SubOpName.empty())
161 throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
162 OpName = OpName.substr(0, DotIdx);
165 unsigned OpIdx = getOperandNamed(OpName);
167 if (SubOpName.empty()) { // If no suboperand name was specified:
168 // If one was needed, throw.
169 if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
171 throw TheDef->getName() + ": Illegal to refer to"
172 " whole operand part of complex operand '" + Op + "'";
174 // Otherwise, return the operand.
175 return std::make_pair(OpIdx, 0U);
178 // Find the suboperand number involved.
179 DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
181 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
183 // Find the operand with the right name.
184 for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
185 if (MIOpInfo->getArgName(i) == SubOpName)
186 return std::make_pair(OpIdx, i);
188 // Otherwise, didn't find it!
189 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
192 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops) {
193 // EARLY_CLOBBER: @early $reg
194 std::string::size_type wpos = CStr.find_first_of(" \t");
195 std::string::size_type start = CStr.find_first_not_of(" \t");
196 std::string Tok = CStr.substr(start, wpos - start);
197 if (Tok == "@earlyclobber") {
198 std::string Name = CStr.substr(wpos+1);
199 wpos = Name.find_first_not_of(" \t");
200 if (wpos == std::string::npos)
201 throw "Illegal format for @earlyclobber constraint: '" + CStr + "'";
202 Name = Name.substr(wpos);
203 std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
205 // Build the string for the operand
206 if (!Ops[Op.first].Constraints[Op.second].isNone())
207 throw "Operand '" + Name + "' cannot have multiple constraints!";
208 Ops[Op.first].Constraints[Op.second] =
209 CGIOperandList::ConstraintInfo::getEarlyClobber();
213 // Only other constraint is "TIED_TO" for now.
214 std::string::size_type pos = CStr.find_first_of('=');
215 assert(pos != std::string::npos && "Unrecognized constraint");
216 start = CStr.find_first_not_of(" \t");
217 std::string Name = CStr.substr(start, pos - start);
219 // TIED_TO: $src1 = $dst
220 wpos = Name.find_first_of(" \t");
221 if (wpos == std::string::npos)
222 throw "Illegal format for tied-to constraint: '" + CStr + "'";
223 std::string DestOpName = Name.substr(0, wpos);
224 std::pair<unsigned,unsigned> DestOp = Ops.ParseOperandName(DestOpName, false);
226 Name = CStr.substr(pos+1);
227 wpos = Name.find_first_not_of(" \t");
228 if (wpos == std::string::npos)
229 throw "Illegal format for tied-to constraint: '" + CStr + "'";
231 std::pair<unsigned,unsigned> SrcOp =
232 Ops.ParseOperandName(Name.substr(wpos), false);
234 throw "Illegal tied-to operand constraint '" + CStr + "'";
237 unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
239 if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
240 throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
241 Ops[DestOp.first].Constraints[DestOp.second] =
242 CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
245 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
246 if (CStr.empty()) return;
248 const std::string delims(",");
249 std::string::size_type bidx, eidx;
251 bidx = CStr.find_first_not_of(delims);
252 while (bidx != std::string::npos) {
253 eidx = CStr.find_first_of(delims, bidx);
254 if (eidx == std::string::npos)
255 eidx = CStr.length();
257 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
258 bidx = CStr.find_first_not_of(delims, eidx);
262 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
265 tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
266 if (OpName.empty()) break;
268 // Figure out which operand this is.
269 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
271 // Mark the operand as not-to-be encoded.
272 if (Op.second >= OperandList[Op.first].DoNotEncode.size())
273 OperandList[Op.first].DoNotEncode.resize(Op.second+1);
274 OperandList[Op.first].DoNotEncode[Op.second] = true;
279 //===----------------------------------------------------------------------===//
280 // CodeGenInstruction Implementation
281 //===----------------------------------------------------------------------===//
283 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
284 Namespace = R->getValueAsString("Namespace");
285 AsmString = R->getValueAsString("AsmString");
287 isReturn = R->getValueAsBit("isReturn");
288 isBranch = R->getValueAsBit("isBranch");
289 isIndirectBranch = R->getValueAsBit("isIndirectBranch");
290 isCompare = R->getValueAsBit("isCompare");
291 isMoveImm = R->getValueAsBit("isMoveImm");
292 isBitcast = R->getValueAsBit("isBitcast");
293 isBarrier = R->getValueAsBit("isBarrier");
294 isCall = R->getValueAsBit("isCall");
295 canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
296 mayLoad = R->getValueAsBit("mayLoad");
297 mayStore = R->getValueAsBit("mayStore");
298 isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
299 isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
300 isCommutable = R->getValueAsBit("isCommutable");
301 isTerminator = R->getValueAsBit("isTerminator");
302 isReMaterializable = R->getValueAsBit("isReMaterializable");
303 hasDelaySlot = R->getValueAsBit("hasDelaySlot");
304 usesCustomInserter = R->getValueAsBit("usesCustomInserter");
305 hasCtrlDep = R->getValueAsBit("hasCtrlDep");
306 isNotDuplicable = R->getValueAsBit("isNotDuplicable");
307 hasSideEffects = R->getValueAsBit("hasSideEffects");
308 neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
309 isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
310 hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
311 hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
312 ImplicitDefs = R->getValueAsListOfDefs("Defs");
313 ImplicitUses = R->getValueAsListOfDefs("Uses");
315 if (neverHasSideEffects + hasSideEffects > 1)
316 throw R->getName() + ": multiple conflicting side-effect flags set!";
318 // Parse Constraints.
319 ParseConstraints(R->getValueAsString("Constraints"), Operands);
321 // Parse the DisableEncoding field.
322 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
325 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
326 /// implicit def and it has a known VT, return the VT, otherwise return
328 MVT::SimpleValueType CodeGenInstruction::
329 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
330 if (ImplicitDefs.empty()) return MVT::Other;
332 // Check to see if the first implicit def has a resolvable type.
333 Record *FirstImplicitDef = ImplicitDefs[0];
334 assert(FirstImplicitDef->isSubClassOf("Register"));
335 const std::vector<MVT::SimpleValueType> &RegVTs =
336 TargetInfo.getRegisterVTs(FirstImplicitDef);
337 if (RegVTs.size() == 1)
343 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
344 /// include text from the specified variant, returning the new string.
345 std::string CodeGenInstruction::
346 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
347 std::string Res = "";
350 // Find the start of the next variant string.
351 size_t VariantsStart = 0;
352 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
353 if (Cur[VariantsStart] == '{' &&
354 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
355 Cur[VariantsStart-1] != '\\')))
358 // Add the prefix to the result.
359 Res += Cur.slice(0, VariantsStart);
360 if (VariantsStart == Cur.size())
363 ++VariantsStart; // Skip the '{'.
365 // Scan to the end of the variants string.
366 size_t VariantsEnd = VariantsStart;
367 unsigned NestedBraces = 1;
368 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
369 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
370 if (--NestedBraces == 0)
372 } else if (Cur[VariantsEnd] == '{')
376 // Select the Nth variant (or empty).
377 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
378 for (unsigned i = 0; i != Variant; ++i)
379 Selection = Selection.split('|').second;
380 Res += Selection.split('|').first;
382 assert(VariantsEnd != Cur.size() &&
383 "Unterminated variants in assembly string!");
384 Cur = Cur.substr(VariantsEnd + 1);
391 //===----------------------------------------------------------------------===//
392 /// CodeGenInstAlias Implementation
393 //===----------------------------------------------------------------------===//
395 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
396 /// constructor. It checks if an argument in an InstAlias pattern matches
397 /// the corresponding operand of the instruction. It returns true on a
398 /// successful match, with ResOp set to the result operand to be used.
399 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
400 Record *InstOpRec, bool hasSubOps,
401 SMLoc Loc, CodeGenTarget &T,
402 ResultOperand &ResOp) {
403 Init *Arg = Result->getArg(AliasOpNo);
404 DefInit *ADI = dynamic_cast<DefInit*>(Arg);
406 if (ADI && ADI->getDef() == InstOpRec) {
407 // If the operand is a record, it must have a name, and the record type
408 // must match up with the instruction's argument type.
409 if (Result->getArgName(AliasOpNo).empty())
410 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
411 " must have a name!");
412 ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
416 // Handle explicit registers.
417 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
418 if (!InstOpRec->isSubClassOf("RegisterClass"))
421 if (!T.getRegisterClass(InstOpRec)
422 .contains(T.getRegBank().getReg(ADI->getDef())))
423 throw TGError(Loc, "fixed register " +ADI->getDef()->getName()
424 + " is not a member of the " + InstOpRec->getName() +
427 if (!Result->getArgName(AliasOpNo).empty())
428 throw TGError(Loc, "result fixed register argument must "
431 ResOp = ResultOperand(ADI->getDef());
435 // Handle "zero_reg" for optional def operands.
436 if (ADI && ADI->getDef()->getName() == "zero_reg") {
438 // Check if this is an optional def.
439 if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
440 throw TGError(Loc, "reg0 used for result that is not an "
441 "OptionalDefOperand!");
443 ResOp = ResultOperand(static_cast<Record*>(0));
447 if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
448 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
450 // Integer arguments can't have names.
451 if (!Result->getArgName(AliasOpNo).empty())
452 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
453 " must not have a name!");
454 ResOp = ResultOperand(II->getValue());
461 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
462 AsmString = R->getValueAsString("AsmString");
463 Result = R->getValueAsDag("ResultInst");
465 // Verify that the root of the result is an instruction.
466 DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
467 if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
468 throw TGError(R->getLoc(), "result of inst alias should be an instruction");
470 ResultInst = &T.getInstruction(DI->getDef());
472 // NameClass - If argument names are repeated, we need to verify they have
474 StringMap<Record*> NameClass;
475 for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
476 DefInit *ADI = dynamic_cast<DefInit*>(Result->getArg(i));
477 if (!ADI || Result->getArgName(i).empty())
479 // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
480 // $foo can exist multiple times in the result list, but it must have the
482 Record *&Entry = NameClass[Result->getArgName(i)];
483 if (Entry && Entry != ADI->getDef())
484 throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
485 " is both " + Entry->getName() + " and " +
486 ADI->getDef()->getName() + "!");
487 Entry = ADI->getDef();
490 // Decode and validate the arguments of the result.
491 unsigned AliasOpNo = 0;
492 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
494 // Tied registers don't have an entry in the result dag.
495 if (ResultInst->Operands[i].getTiedRegister() != -1)
498 if (AliasOpNo >= Result->getNumArgs())
499 throw TGError(R->getLoc(), "not enough arguments for instruction!");
501 Record *InstOpRec = ResultInst->Operands[i].Rec;
502 unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
503 ResultOperand ResOp(static_cast<int64_t>(0));
504 if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
505 R->getLoc(), T, ResOp)) {
506 ResultOperands.push_back(ResOp);
507 ResultInstOperandIndex.push_back(std::make_pair(i, -1));
512 // If the argument did not match the instruction operand, and the operand
513 // is composed of multiple suboperands, try matching the suboperands.
515 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
516 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
517 if (AliasOpNo >= Result->getNumArgs())
518 throw TGError(R->getLoc(), "not enough arguments for instruction!");
519 Record *SubRec = dynamic_cast<DefInit*>(MIOI->getArg(SubOp))->getDef();
520 if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
521 R->getLoc(), T, ResOp)) {
522 ResultOperands.push_back(ResOp);
523 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
526 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
527 " does not match instruction operand class " +
528 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
533 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
534 " does not match instruction operand class " +
535 InstOpRec->getName());
538 if (AliasOpNo != Result->getNumArgs())
539 throw TGError(R->getLoc(), "too many operands for instruction!");