llvm.org GIT mirror llvm / 02dea26
TableGen: Streamline how defs are instantiated Summary: Instantiating def's and defm's needs to perform the following steps: - for defm's, clone multiclass def prototypes and subsitute template args - for def's and defm's, add subclass definitions, substituting template args - clone the record based on foreach loops and substitute loop iteration variables - override record variables based on the global 'let' stack - resolve the record name (this should be simple, but unfortunately it's not due to existing .td files relying on rather silly implementation details) - for def(m)s in multiclasses, add the unresolved record as a multiclass prototype - for top-level def(m)s, resolve all internal variable references and add them to the record keeper and any active defsets This change streamlines how we go through these steps, by having both def's and defm's feed into a single addDef() method that handles foreach, final resolve, and routing the record to the right place. This happens to make foreach inside of multiclasses work, as the new test case demonstrates. Previously, foreach inside multiclasses was not forbidden by the parser, but it was de facto broken. Another side effect is that the order of "instantiated from" notes in error messages is reversed, as the modified test case shows. This is arguably clearer, since the initial error message ends up pointing directly to whatever triggered the error, and subsequent notes will point to increasingly outer layers of multiclasses. This is consistent with how C++ compilers report nested #includes and nested template instantiations. Change-Id: Ica146d0db2bc133dd7ed88054371becf24320447 Reviewers: arsenm, craig.topper, tra, MartinO Subscribers: wdng, llvm-commits Differential Revision: https://reviews.llvm.org/D44478 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@328117 91177308-0d34-0410-b5e6-96231b3b80d8 Nicolai Haehnle 1 year, 6 months ago
8 changed file(s) with 338 addition(s) and 414 deletion(s). Raw diff Collapse all Expand all
13691369 init();
13701370 }
13711371
1372 explicit Record(StringRef N, ArrayRef locs, RecordKeeper &records,
1373 bool Anonymous = false)
1374 : Record(StringInit::get(N), locs, records, Anonymous) {}
1372 explicit Record(StringRef N, ArrayRef locs, RecordKeeper &records)
1373 : Record(StringInit::get(N), locs, records) {}
13751374
13761375 // When copy-constructing a Record, we must still guarantee a globally unique
13771376 // ID number. Don't copy TheInit either since it's owned by the original
13991398 void setName(Init *Name); // Also updates RecordKeeper.
14001399
14011400 ArrayRef getLoc() const { return Locs; }
1401 void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
1402
1403 // Make the type that this record should have based on its superclasses.
1404 RecordRecTy *getType();
14021405
14031406 /// get the corresponding DefInit.
14041407 DefInit *getDefInit();
14901493 }
14911494
14921495 void addSuperClass(Record *R, SMRange Range) {
1496 assert(!TheInit && "changing type of record after it has been referenced");
14931497 assert(!isSubClassOf(R) && "Already subclassing record!");
14941498 SuperClasses.push_back(std::make_pair(R, Range));
14951499 }
15071507 return VarBitInit::get(const_cast(this), Bit);
15081508 }
15091509
1510 static RecordRecTy *makeDefInitType(Record *Rec) {
1511 SmallVector SuperClasses;
1512 Rec->getDirectSuperClasses(SuperClasses);
1513 return RecordRecTy::get(SuperClasses);
1514 }
1515
15161510 DefInit::DefInit(Record *D)
1517 : TypedInit(IK_DefInit, makeDefInitType(D)), Def(D) {}
1511 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
15181512
15191513 DefInit *DefInit::get(Record *R) {
15201514 return R->getDefInit();
18641858 // Ensure the record name has string type.
18651859 const TypedInit *TypedName = cast(Name);
18661860 if (!isa(TypedName->getType()))
1867 PrintFatalError(getLoc(), "Record name is not a string!");
1861 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
1862 "' is not a string!");
1863 }
1864
1865 RecordRecTy *Record::getType() {
1866 SmallVector DirectSCs;
1867 getDirectSuperClasses(DirectSCs);
1868 return RecordRecTy::get(DirectSCs);
18681869 }
18691870
18701871 DefInit *Record::getDefInit() {
336336 return false;
337337 }
338338
339 /// ProcessForeachDefs - Given a record, apply all of the variable
340 /// values in all surrounding foreach loops, creating new records for
341 /// each combination of values.
342 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
339 /// Add a record that results from 'def' or 'defm', after template arguments
340 /// and the external let stack have been resolved.
341 ///
342 /// Apply foreach loops, resolve internal variable references, and add to the
343 /// current multi class or the global record keeper as appropriate.
344 bool TGParser::addDef(std::unique_ptr Rec, Init *DefmName) {
345 IterSet IterVals;
346
343347 if (Loops.empty())
344 return false;
345
346 // We want to instantiate a new copy of CurRec for each combination
347 // of nested loop iterator values. We don't want top instantiate
348 // any copies until we have values for each loop iterator.
349 IterSet IterVals;
350 return ProcessForeachDefs(CurRec, Loc, IterVals);
351 }
352
353 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
354 /// apply each of the variable values in this loop and then process
355 /// subloops.
356 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
357 // Recursively build a tuple of iterator values.
348 return addDefOne(std::move(Rec), DefmName, IterVals);
349
350 return addDefForeach(Rec.get(), DefmName, IterVals);
351 }
352
353 /// Recursive helper function for addDef/addDefOne to resolve references to
354 /// foreach variables.
355 bool TGParser::addDefForeach(Record *Rec, Init *DefmName, IterSet &IterVals) {
358356 if (IterVals.size() != Loops.size()) {
359357 assert(IterVals.size() < Loops.size());
360358 ForeachLoop &CurLoop = Loops[IterVals.size()];
361 ListInit *List = dyn_cast(CurLoop.ListValue);
362 if (!List) {
363 Error(Loc, "Loop list is not a list");
364 return true;
365 }
359 ListInit *List = CurLoop.ListValue;
366360
367361 // Process each value.
368362 for (unsigned i = 0; i < List->size(); ++i) {
369 RecordResolver R(*CurRec);
370 Init *ItemVal = List->getElement(i)->resolveReferences(R);
371 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
372 if (ProcessForeachDefs(CurRec, Loc, IterVals))
363 IterVals.push_back(IterRecord(CurLoop.IterVar, List->getElement(i)));
364 if (addDefForeach(Rec, DefmName, IterVals))
373365 return true;
374366 IterVals.pop_back();
375367 }
379371 // This is the bottom of the recursion. We have all of the iterator values
380372 // for this point in the iteration space. Instantiate a new record to
381373 // reflect this combination of values.
382 auto IterRec = make_unique(*CurRec);
383
384 // Set the iterator values now.
385 for (IterRecord &IR : IterVals) {
386 VarInit *IterVar = IR.IterVar;
387 TypedInit *IVal = dyn_cast(IR.IterValue);
388 if (!IVal)
389 return Error(Loc, "foreach iterator value is untyped");
390
391 IterRec->addValue(RecordVal(IterVar->getNameInit(), IVal->getType(), false));
392
393 if (SetValue(IterRec.get(), Loc, IterVar->getNameInit(), None, IVal))
394 return Error(Loc, "when instantiating this def");
395
396 // Resolve it next.
397 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getNameInit()));
398
399 // Remove it.
400 IterRec->removeValue(IterVar->getNameInit());
401 }
402
403 if (Records.getDef(IterRec->getNameInitAsString())) {
404 // If this record is anonymous, it's no problem, just generate a new name
405 if (!IterRec->isAnonymous())
406 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
407
408 IterRec->setName(Records.getNewAnonymousName());
409 }
410
411 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
412 Records.addDef(std::move(IterRec));
413 IterRecSave->resolveReferences();
414 checkConcrete(*IterRecSave);
415 if (addToDefsets(*IterRecSave))
416 return true;
374 auto IterRec = make_unique(*Rec);
375 return addDefOne(std::move(IterRec), DefmName, IterVals);
376 }
377
378 /// After resolving foreach loops, add the record as a prototype to the
379 /// current multiclass, or resolve fully and add to the record keeper.
380 bool TGParser::addDefOne(std::unique_ptr Rec, Init *DefmName,
381 IterSet &IterVals) {
382 MapResolver R(Rec.get());
383
384 for (IterRecord &IR : IterVals)
385 R.set(IR.IterVar->getNameInit(), IR.IterValue);
386
387 Rec->resolveReferences(R);
388
389 if (CurMultiClass) {
390 for (const auto &Proto : CurMultiClass->DefPrototypes) {
391 if (Proto->getNameInit() == Rec->getNameInit()) {
392 if (!Rec->isAnonymous()) {
393 PrintError(Rec->getLoc(),
394 Twine("def '") + Rec->getNameInitAsString() +
395 "' already defined in this multiclass!");
396 PrintNote(Proto->getLoc(), "location of previous definition");
397 return true;
398 }
399 Rec->setName(Records.getNewAnonymousName());
400 break;
401 }
402 }
403 CurMultiClass->DefPrototypes.emplace_back(std::move(Rec));
404 return false;
405 }
406
407 // Name construction is an incoherent mess. Unfortunately, existing .td
408 // files rely on pretty much all the quirks and implementation details of
409 // this.
410 if (DefmName) {
411 MapResolver R(Rec.get());
412 R.set(StringInit::get("NAME"), DefmName);
413 Rec->resolveReferences(R);
414 }
415
416 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
417 if (!Rec->isAnonymous()) {
418 PrintError(Rec->getLoc(),
419 "def already exists: " + Rec->getNameInitAsString());
420 PrintNote(Prev->getLoc(), "location of previous definition");
421 return true;
422 }
423 Rec->setName(Records.getNewAnonymousName());
424 }
425
426 Rec->resolveReferences();
427 checkConcrete(*Rec);
428
429 // If ObjectBody has template arguments, it's an error.
430 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
431
432 for (DefsetRecord *Defset : Defsets) {
433 DefInit *I = Rec->getDefInit();
434 if (!I->getType()->typeIsA(Defset->EltTy)) {
435 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
436 I->getType()->getAsString() +
437 "' to defset");
438 PrintNote(Defset->Loc, "location of defset declaration");
439 return true;
440 }
441 Defset->Elements.push_back(I);
442 }
443
444 Records.addDef(std::move(Rec));
417445 return false;
418446 }
419447
428456 K == tgtok::Defset;
429457 }
430458
431 /// ParseObjectName - If an object name is specified, return it. Otherwise,
432 /// return 0.
459 /// ParseObjectName - If a valid object name is specified, return it. If no
460 /// name is specified, return the unset initializer. Return nullptr on parse
461 /// error.
433462 /// ObjectName ::= Value [ '#' Value ]*
434463 /// ObjectName ::= /*empty*/
435464 ///
441470 // These are all of the tokens that can begin an object body.
442471 // Some of these can also begin values but we disallow those cases
443472 // because they are unlikely to be useful.
444 return nullptr;
473 return UnsetInit::get();
445474 default:
446475 break;
447476 }
450479 if (CurMultiClass)
451480 CurRec = &CurMultiClass->Rec;
452481
453 RecTy *Type = nullptr;
454 if (CurRec) {
455 const TypedInit *CurRecName = dyn_cast(CurRec->getNameInit());
456 if (!CurRecName) {
457 TokError("Record name is not typed!");
458 return nullptr;
459 }
460 Type = CurRecName->getType();
461 }
462
463 return ParseValue(CurRec, Type, ParseNameMode);
482 return ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
464483 }
465484
466485 /// ParseClassID - Parse and resolve a reference to a class name. This returns
809828
810829 if (Init *I = Records.getGlobal(Name->getValue()))
811830 return I;
831
832 // Allow self-references of concrete defs, but delay the lookup so that we
833 // get the correct type.
834 if (CurRec && !CurMultiClass && CurRec->getNameInit() == Name)
835 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
812836
813837 if (Mode == ParseValueMode) {
814838 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
22232247 if (TypedInit *TI = dyn_cast(I))
22242248 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
22252249 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2250 if (CurMultiClass)
2251 PrintNote({}, "references to multiclass template arguments cannot be "
2252 "resolved at this time");
22262253 return nullptr;
22272254 }
22282255 ForeachListValue = dyn_cast(I);
24152442 Lex.Lex(); // Eat the 'def' token.
24162443
24172444 // Parse ObjectName and make a record for it.
2418 std::unique_ptr CurRecOwner;
2445 std::unique_ptr CurRec;
24192446 Init *Name = ParseObjectName(CurMultiClass);
2420 if (Name)
2421 CurRecOwner = make_unique(Name, DefLoc, Records);
2447 if (!Name)
2448 return true;
2449
2450 if (isa(Name))
2451 CurRec = make_unique(Records.getNewAnonymousName(), DefLoc, Records,
2452 /*Anonymous=*/true);
24222453 else
2423 CurRecOwner = make_unique(Records.getNewAnonymousName(), DefLoc,
2424 Records, /*IsAnonymous=*/true);
2425 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2426
2427 if (!CurMultiClass && Loops.empty()) {
2428 // Top-level def definition.
2429
2430 // Ensure redefinition doesn't happen.
2431 if (Records.getDef(CurRec->getNameInitAsString()))
2432 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2433 "' already defined");
2434 Records.addDef(std::move(CurRecOwner));
2435
2436 if (ParseObjectBody(CurRec))
2437 return true;
2438 } else if (CurMultiClass) {
2439 // Parse the body before adding this prototype to the DefPrototypes vector.
2440 // That way implicit definitions will be added to the DefPrototypes vector
2441 // before this object, instantiated prior to defs derived from this object,
2442 // and this available for indirect name resolution when defs derived from
2443 // this object are instantiated.
2444 if (ParseObjectBody(CurRec))
2445 return true;
2446
2447 // Otherwise, a def inside a multiclass, add it to the multiclass.
2448 for (const auto &Proto : CurMultiClass->DefPrototypes)
2449 if (Proto->getNameInit() == CurRec->getNameInit())
2450 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2451 "' already defined in this multiclass!");
2452 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2453 } else if (ParseObjectBody(CurRec)) {
2454 CurRec = make_unique(Name, DefLoc, Records);
2455
2456 if (ParseObjectBody(CurRec.get()))
24542457 return true;
2455 }
2456
2457 if (!CurMultiClass) { // Def's in multiclasses aren't really defs.
2458 // See Record::setName(). This resolve step will see any new name
2459 // for the def that might have been created when resolving
2460 // inheritance, values and arguments above.
2461 CurRec->resolveReferences();
2462 if (Loops.empty()) {
2463 checkConcrete(*CurRec);
2464 if (addToDefsets(*CurRec))
2465 return true;
2466 }
2467 }
2468
2469 // If ObjectBody has template arguments, it's an error.
2470 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2471
2472 if (CurMultiClass) {
2473 // Copy the template arguments for the multiclass into the def.
2474 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2475 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2476 assert(RV && "Template arg doesn't exist?");
2477 CurRec->addValue(*RV);
2478 }
2479 }
2480
2481 if (ProcessForeachDefs(CurRec, DefLoc))
2482 return Error(DefLoc, "Could not process loops for def" +
2483 CurRec->getNameInitAsString());
2484
2485 return false;
2486 }
2487
2488 bool TGParser::addToDefsets(Record &R) {
2489 for (DefsetRecord *Defset : Defsets) {
2490 DefInit *I = R.getDefInit();
2491 if (!I->getType()->typeIsA(Defset->EltTy)) {
2492 PrintError(R.getLoc(),
2493 Twine("adding record of incompatible type '") +
2494 I->getType()->getAsString() + "' to defset");
2495 PrintNote(Defset->Loc, "to this defset");
2496 return true;
2497 }
2498 Defset->Elements.push_back(I);
2499 }
2500 return false;
2458
2459 return addDef(std::move(CurRec), nullptr);
25012460 }
25022461
25032462 /// ParseDefset - Parse a defset statement.
28172776 return false;
28182777 }
28192778
2820 Record *TGParser::InstantiateMulticlassDef(MultiClass &MC, Record *DefProto,
2821 Init *&DefmPrefix,
2822 SMRange DefmPrefixRange,
2823 ArrayRef TArgs,
2824 ArrayRef TemplateVals) {
2825 // We need to preserve DefProto so it can be reused for later
2826 // instantiations, so create a new Record to inherit from it.
2827
2828 // Add in the defm name. If the defm prefix is empty, give each
2829 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2830 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2831 // as a prefix.
2832
2833 bool IsAnonymous = false;
2834 if (!DefmPrefix) {
2835 DefmPrefix = Records.getNewAnonymousName();
2836 IsAnonymous = true;
2837 }
2838
2839 Init *DefName = DefProto->getNameInit();
2840 StringInit *DefNameString = dyn_cast(DefName);
2841
2842 if (DefNameString) {
2843 // We have a fully expanded string so there are no operators to
2844 // resolve. We should concatenate the given prefix and name.
2845 DefName = BinOpInit::getStrConcat(
2846 UnOpInit::get(UnOpInit::CAST, DefmPrefix, StringRecTy::get())
2847 ->Fold(DefProto),
2848 DefName);
2849 }
2850
2851 // Make a trail of SMLocs from the multiclass instantiations.
2852 SmallVector Locs(1, DefmPrefixRange.Start);
2853 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2854 auto CurRec = make_unique(DefName, Locs, Records, IsAnonymous);
2855
2856 SubClassReference Ref;
2857 Ref.RefRange = DefmPrefixRange;
2858 Ref.Rec = DefProto;
2859 AddSubClass(CurRec.get(), Ref);
2860
2861 // Set the value for NAME. We don't resolve references to it 'til later,
2862 // though, so that uses in nested multiclass names don't get
2863 // confused.
2864 if (SetValue(CurRec.get(), Ref.RefRange.Start, StringInit::get("NAME"), None,
2865 DefmPrefix, /*AllowSelfAssignment*/true)) {
2866 Error(DefmPrefixRange.Start, "Could not resolve " +
2867 CurRec->getNameInitAsString() + ":NAME to '" +
2868 DefmPrefix->getAsUnquotedString() + "'");
2869 return nullptr;
2870 }
2871
2872 // If the DefNameString didn't resolve, we probably have a reference to
2873 // NAME and need to replace it. We need to do at least this much greedily,
2874 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2875 if (!DefNameString) {
2876 RecordVal *DefNameRV = CurRec->getValue("NAME");
2877 CurRec->resolveReferencesTo(DefNameRV);
2878 }
2879
2880 if (!CurMultiClass) {
2881 // Now that we're at the top level, resolve all NAME references
2882 // in the resultant defs that weren't in the def names themselves.
2883 RecordVal *DefNameRV = CurRec->getValue("NAME");
2884 CurRec->resolveReferencesTo(DefNameRV);
2885
2886 // Check if the name is a complex pattern.
2887 // If so, resolve it.
2888 DefName = CurRec->getNameInit();
2889 DefNameString = dyn_cast(DefName);
2890
2891 // OK the pattern is more complex than simply using NAME.
2892 // Let's use the heavy weaponery.
2893 if (!DefNameString) {
2894 ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
2895 Lex.getLoc(), TArgs, TemplateVals,
2896 false/*Delete args*/);
2897 DefName = CurRec->getNameInit();
2898 DefNameString = dyn_cast(DefName);
2899
2900 if (!DefNameString) {
2901 DefName = DefName->convertInitializerTo(StringRecTy::get());
2902 DefNameString = dyn_cast(DefName);
2903 }
2904
2905 if (!DefNameString) {
2906 PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
2907 DefName->getAsUnquotedString() + " is not a string.");
2908 return nullptr;
2909 }
2910
2911 CurRec->setName(DefName);
2912 }
2913
2914 // Now that NAME references are resolved and we're at the top level of
2915 // any multiclass expansions, add the record to the RecordKeeper. If we are
2916 // currently in a multiclass, it means this defm appears inside a
2917 // multiclass and its name won't be fully resolvable until we see
2918 // the top-level defm. Therefore, we don't add this to the
2919 // RecordKeeper at this point. If we did we could get duplicate
2920 // defs as more than one probably refers to NAME or some other
2921 // common internal placeholder.
2922
2923 // Ensure redefinition doesn't happen.
2924 if (Records.getDef(CurRec->getNameInitAsString())) {
2925 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2926 "' already defined, instantiating defm with subdef '" +
2927 DefProto->getNameInitAsString() + "'");
2928 return nullptr;
2929 }
2930
2931 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2932 Records.addDef(std::move(CurRec));
2933 return CurRecSave;
2934 }
2935
2936 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2937 // The unique_ptr in this function at least protects the exits above.
2938 return CurRec.release();
2939 }
2940
2941 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC, Record *CurRec,
2942 SMLoc DefmPrefixLoc, SMLoc SubClassLoc,
2943 ArrayRef TArgs,
2944 ArrayRef TemplateVals,
2945 bool DeleteArgs) {
2946 // Set all template arguments to the specified value or leave them as the
2947 // default if necessary, then resolve them all simultaneously.
2948 MapResolver R(CurRec);
2949
2950 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2951 // Check if a value is specified for this temp-arg.
2952 if (i < TemplateVals.size()) {
2953 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], None, TemplateVals[i]))
2954 return true;
2955 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2956 return Error(SubClassLoc, "value not specified for template argument #" +
2957 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2958 ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
2959 "'");
2960 }
2961
2962 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
2963
2964 if (DeleteArgs)
2965 CurRec->removeValue(TArgs[i]);
2966 }
2967
2968 CurRec->resolveReferences(R);
2969
2970 return false;
2971 }
2972
2973 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2974 Record *CurRec,
2975 Record *DefProto,
2976 SMLoc DefmPrefixLoc) {
2977 // If the mdef is inside a 'let' expression, add to each def.
2978 if (ApplyLetStack(CurRec))
2979 return Error(DefmPrefixLoc, "when instantiating this defm");
2980
2981 // Don't create a top level definition for defm inside multiclasses,
2982 // instead, only update the prototypes and bind the template args
2983 // with the new created definition.
2984 if (!CurMultiClass)
2985 return false;
2986 for (const auto &Proto : CurMultiClass->DefPrototypes)
2987 if (Proto->getNameInit() == CurRec->getNameInit())
2988 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2989 "' already defined in this multiclass!");
2990 CurMultiClass->DefPrototypes.push_back(std::unique_ptr(CurRec));
2991
2992 // Copy the template arguments for the multiclass into the new def.
2993 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2994 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2995 assert(RV && "Template arg doesn't exist?");
2996 CurRec->addValue(*RV);
2997 }
2998
2999 return false;
3000 }
3001
30022779 /// ParseDefm - Parse the instantiation of a multiclass.
30032780 ///
30042781 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
30052782 ///
30062783 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
30072784 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3008 SMLoc DefmLoc = Lex.getLoc();
3009 Init *DefmPrefix = nullptr;
3010
3011 if (Lex.Lex() == tgtok::Id) { // eat the defm.
3012 DefmPrefix = ParseObjectName(CurMultiClass);
3013 }
3014
3015 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2785 Lex.Lex(); // eat the defm
2786
2787 Init *DefmName = ParseObjectName(CurMultiClass);
2788 if (!DefmName)
2789 return true;
2790 if (isa(DefmName))
2791 DefmName = Records.getNewAnonymousName();
2792
30162793 if (Lex.getCode() != tgtok::colon)
30172794 return TokError("expected ':' after defm identifier");
30182795
30192796 // Keep track of the new generated record definitions.
3020 std::vector> NewRecDefs;
2797 SmallVector, 8> NewRecDefs;
30212798
30222799 // This record also inherits from a regular class (non-multiclass)?
30232800 bool InheritFromClass = false;
30442821 return Error(SubClassLoc,
30452822 "more template args specified than multiclass expects");
30462823
2824 DenseMap TemplateArgs;
2825 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2826 if (i < TemplateVals.size()) {
2827 TemplateArgs.insert({TArgs[i], TemplateVals[i]});
2828 } else {
2829 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
2830 if (!Default->isComplete()) {
2831 return Error(SubClassLoc,
2832 "value not specified for template argument #" +
2833 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2834 ") of multiclass '" + MC->Rec.getNameInitAsString() +
2835 "'");
2836 }
2837 TemplateArgs.insert({TArgs[i], Default});
2838 }
2839 }
2840
30472841 // Loop over all the def's in the multiclass, instantiating each one.
30482842 for (const std::unique_ptr &DefProto : MC->DefPrototypes) {
3049 // The record name construction goes as follow:
3050 // - If the def name is a string, prepend the prefix.
3051 // - If the def name is a more complex pattern, use that pattern.
3052 // As a result, the record is instantiated before resolving
3053 // arguments, as it would make its name a string.
3054 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
3055 SMRange(DefmLoc,
3056 DefmPrefixEndLoc),
3057 TArgs, TemplateVals);
3058 if (!CurRec)
3059 return true;
3060
3061 // Now that the record is instantiated, we can resolve arguments.
3062 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
3063 TArgs, TemplateVals, true/*Delete args*/))
3064 return Error(SubClassLoc, "could not instantiate def");
3065
3066 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
3067 return Error(SubClassLoc, "could not instantiate def");
3068
3069 NewRecDefs.push_back(CurRec);
3070 }
3071
2843 bool ResolveName = true;
2844 auto CurRec = make_unique(*DefProto);
2845 CurRec->appendLoc(SubClassLoc);
2846
2847 if (StringInit *NameString =
2848 dyn_cast(CurRec->getNameInit())) {
2849 // We have a fully expanded string so there are no operators to
2850 // resolve. We should concatenate the given prefix and name.
2851 //
2852 // TODO: This MUST happen before template argument resolution. This
2853 // does not make sense and should be changed, but at the time of
2854 // writing, there are existing .td files which rely on this
2855 // implementation detail. It's a bad idea and should be fixed.
2856 // See test/TableGen/name-resolution-consistency.td for some
2857 // examples.
2858 CurRec->setName(BinOpInit::getStrConcat(DefmName, NameString));
2859 ResolveName = false;
2860 }
2861
2862 MapResolver R(CurRec.get());
2863
2864 if (ResolveName) {
2865 // If the proto's name wasn't resolved, we probably have a reference to
2866 // NAME and need to replace it.
2867 //
2868 // TODO: Whether the name is resolved is basically determined by magic.
2869 // Unfortunately, existing .td files depend on it.
2870 R.set(StringInit::get("NAME"), DefmName);
2871 }
2872
2873 for (const auto &TArg : TemplateArgs)
2874 R.set(TArg.first, TArg.second);
2875
2876 CurRec->resolveReferences(R);
2877
2878 NewRecDefs.emplace_back(std::move(CurRec));
2879 }
30722880
30732881 if (Lex.getCode() != tgtok::comma) break;
30742882 Lex.Lex(); // eat ','.
30982906
30992907 // Get the expanded definition prototypes and teach them about
31002908 // the record values the current class to inherit has
3101 for (Record *CurRec : NewRecDefs) {
2909 for (const auto &CurRec : NewRecDefs) {
31022910 // Add it.
3103 if (AddSubClass(CurRec, SubClass))
3104 return true;
3105
3106 if (ApplyLetStack(CurRec))
2911 if (AddSubClass(CurRec.get(), SubClass))
31072912 return true;
31082913 }
31092914
31132918 }
31142919 }
31152920
3116 if (!CurMultiClass) {
3117 for (Record *CurRec : NewRecDefs) {
3118 // See Record::setName(). This resolve step will see any new
3119 // name for the def that might have been created when resolving
3120 // inheritance, values and arguments above.
3121 CurRec->resolveReferences();
3122 checkConcrete(*CurRec);
3123 if (addToDefsets(*CurRec))
3124 return true;
3125 }
2921 for (auto &CurRec : NewRecDefs) {
2922 if (ApplyLetStack(CurRec.get()))
2923 return true;
2924
2925 addDef(std::move(CurRec), DefmName);
31262926 }
31272927
31282928 if (Lex.getCode() != tgtok::semi)
125125 // iteration space.
126126 typedef std::vector IterSet;
127127
128 bool ProcessForeachDefs(Record *CurRec, SMLoc Loc);
129 bool ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals);
130
131 bool addToDefsets(Record &R);
128 bool addDefOne(std::unique_ptr Rec, Init *DefmName,
129 IterSet &IterVals);
130 bool addDefForeach(Record *Rec, Init *DefmName, IterSet &IterVals);
131 bool addDef(std::unique_ptr Rec, Init *DefmName);
132132
133133 private: // Parser methods.
134134 bool ParseObjectList(MultiClass *MC = nullptr);
135135 bool ParseObject(MultiClass *MC);
136136 bool ParseClass();
137137 bool ParseMultiClass();
138 Record *InstantiateMulticlassDef(MultiClass &MC, Record *DefProto,
139 Init *&DefmPrefix, SMRange DefmPrefixRange,
140 ArrayRef TArgs,
141 ArrayRef TemplateVals);
142 bool ResolveMulticlassDefArgs(MultiClass &MC, Record *DefProto,
143 SMLoc DefmPrefixLoc, SMLoc SubClassLoc,
144 ArrayRef TArgs,
145 ArrayRef TemplateVals, bool DeleteArgs);
146 bool ResolveMulticlassDef(MultiClass &MC,
147 Record *CurRec,
148 Record *DefProto,
149 SMLoc DefmPrefixLoc);
150138 bool ParseDefm(MultiClass *CurMultiClass);
151139 bool ParseDef(MultiClass *CurMultiClass);
152140 bool ParseDefset();
2323 defm _m1: M0;
2424 }
2525
26 // CHECK: defm d1: M1
26 // CHECK: def _m01: B
2727 // CHECK: note: instantiated from multiclass
2828 // CHECK: defm _m1: M0
2929 // CHECK: note: instantiated from multiclass
30 // CHECK: def _m01: B
30 // CHECK: defm d1: M1
3131 defm d1: M1<"d1">;
0 // RUN: llvm-tblgen %s | FileCheck %s
1 // XFAIL: vg_leak
2
3 // CHECK: --- Defs ---
4
5 // CHECK: def A00 {
6 // CHECK: int sum = 7;
7 // CHECK: }
8
9 // CHECK: def A01 {
10 // CHECK: int sum = 8;
11 // CHECK: }
12
13 multiclass A {
14 // Allow foreach in multiclass as long as the list does not depend on
15 // template args.
16 foreach i = [0, 1] in {
17 def NAME#i {
18 int sum = !add(x, i);
19 }
20 }
21 }
22
23 defm A0 : A<7>;
0 // RUN: llvm-tblgen %s | FileCheck %s
1 // XFAIL: vg_leak
2
3 // This test demonstrates a number of inconsistencies in how NAME is resolved
4 // and record names are constructed.
5 //
6 // The TODO lines describe a suggested consistent behavior that would result
7 // from:
8 // (1) Treating NAME as an implicit multiclass template argument and
9 // (2) always storing the name of (non-anonymous) prototype records in
10 // multiclasses with at least one explicit reference to NAME.
11 //
12 // Unfortunately, several backends (including X86) rely quite heavily on the
13 // current inconsistent behavior and would have to be fixed.
14
15 // CHECK: def B0a {
16 // CHECK: string e = "B0";
17 // CHECK: }
18
19 // CHECK: def B0ba {
20 // TODO: expect "B0b" here
21 // CHECK: string a = "B0";
22 // CHECK: string b = "B0";
23 // CHECK: }
24
25 // CHECK: def B0cza {
26 // TODO: expect "B0cz" here
27 // CHECK: string a = "B0";
28 // CHECK: string b = "B0";
29 // CHECK: }
30
31 // TODO: expect this to be named 'xB0b'
32 // CHECK: def B0xb {
33 // TODO: expect "B0b" here
34 // CHECK: string c = "b";
35 // CHECK: string d = "b";
36 // CHECK: }
37
38 // TODO: expect this to be named B0bys
39 // CHECK: def B0ys {
40 // TODO: expect "B0b" here
41 // CHECK: string f = "b";
42 // CHECK: string g = "b";
43 // CHECK: }
44
45 // CHECK: def xB0cz {
46 // CHECK: string c = "B0cz";
47 // CHECK: string d = "B0cz";
48 // CHECK: }
49
50 // TODO: expect this to be named B0czyt
51 // CHECK: def yt {
52 // CHECK: string f = "B0cz";
53 // CHECK: string g = "B0cz";
54 // CHECK: }
55
56 multiclass A {
57 def a {
58 string a = NAME;
59 string b = p;
60 }
61
62 def x # NAME {
63 string c = NAME;
64 string d = p;
65 }
66
67 def y # q {
68 string f = NAME;
69 string g = p;
70 }
71 }
72
73 multiclass B {
74 def a {
75 string e = NAME;
76 }
77
78 defm b : A;
79
80 defm NAME # c # name : A;
81 }
82
83 defm B0 : B<"z", "t">;
2121
2222 // CHECK: def E0 {
2323 // CHECK: E e = E0;
24 // CHECK: }
25
26 // CHECK: def F0 {
27 // CHECK: Fa as_a = F0;
28 // CHECK: Fb as_b = F0;
29 // CHECK: }
30 // CHECK: def F0x {
31 // CHECK: Fc as_c = F0;
2432 // CHECK: }
2533
2634 def ops;
7280 // work here because E0 does not yet have E as a superclass while the template
7381 // arguments are being parsed.
7482 def E0 : E("E0")>;
83
84 // Ensure that records end up with the correct type even when direct self-
85 // references are involved.
86 class Fa;
87 class Fb {
88 Fa as_a = x;
89 }
90 class Fc {
91 Fb as_b = x;
92 }
93
94 def F0 : Fa, Fb, Fc;
95 def F0x {
96 Fc as_c = F0;
97 }