LLVM 18.0.0git
SelectionDAGISel.cpp
Go to the documentation of this file.
1//===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAGISel class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ScheduleDAGSDNodes.h"
15#include "SelectionDAGBuilder.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringRef.h"
27#include "llvm/Analysis/CFG.h"
64#include "llvm/IR/BasicBlock.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
69#include "llvm/IR/DebugLoc.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsWebAssembly.h"
80#include "llvm/IR/Metadata.h"
81#include "llvm/IR/Statepoint.h"
82#include "llvm/IR/Type.h"
83#include "llvm/IR/User.h"
84#include "llvm/IR/Value.h"
86#include "llvm/MC/MCInstrDesc.h"
87#include "llvm/Pass.h"
93#include "llvm/Support/Debug.h"
96#include "llvm/Support/Timer.h"
102#include <algorithm>
103#include <cassert>
104#include <cstdint>
105#include <iterator>
106#include <limits>
107#include <memory>
108#include <optional>
109#include <string>
110#include <utility>
111#include <vector>
112
113using namespace llvm;
114
115#define DEBUG_TYPE "isel"
116
117STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
118STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
119STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
120STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
121STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
122STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
123STATISTIC(NumFastIselFailLowerArguments,
124 "Number of entry blocks where fast isel failed to lower arguments");
125
127 "fast-isel-abort", cl::Hidden,
128 cl::desc("Enable abort calls when \"fast\" instruction selection "
129 "fails to lower an instruction: 0 disable the abort, 1 will "
130 "abort but for args, calls and terminators, 2 will also "
131 "abort for argument lowering, and 3 will never fallback "
132 "to SelectionDAG."));
133
135 "fast-isel-report-on-fallback", cl::Hidden,
136 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
137 "falls back to SelectionDAG."));
138
139static cl::opt<bool>
140UseMBPI("use-mbpi",
141 cl::desc("use Machine Branch Probability Info"),
142 cl::init(true), cl::Hidden);
143
144#ifndef NDEBUG
147 cl::desc("Only display the basic block whose name "
148 "matches this for all view-*-dags options"));
149static cl::opt<bool>
150ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
151 cl::desc("Pop up a window to show dags before the first "
152 "dag combine pass"));
153static cl::opt<bool>
154ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
155 cl::desc("Pop up a window to show dags before legalize types"));
156static cl::opt<bool>
157 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
158 cl::desc("Pop up a window to show dags before the post "
159 "legalize types dag combine pass"));
160static cl::opt<bool>
161 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
162 cl::desc("Pop up a window to show dags before legalize"));
163static cl::opt<bool>
164ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
165 cl::desc("Pop up a window to show dags before the second "
166 "dag combine pass"));
167static cl::opt<bool>
168ViewISelDAGs("view-isel-dags", cl::Hidden,
169 cl::desc("Pop up a window to show isel dags as they are selected"));
170static cl::opt<bool>
171ViewSchedDAGs("view-sched-dags", cl::Hidden,
172 cl::desc("Pop up a window to show sched dags as they are processed"));
173static cl::opt<bool>
174ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
175 cl::desc("Pop up a window to show SUnit dags after they are processed"));
176#else
177static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
178 ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
179 ViewDAGCombine2 = false, ViewISelDAGs = false,
180 ViewSchedDAGs = false, ViewSUnitDAGs = false;
181#endif
182
183//===---------------------------------------------------------------------===//
184///
185/// RegisterScheduler class - Track the registration of instruction schedulers.
186///
187//===---------------------------------------------------------------------===//
190
191//===---------------------------------------------------------------------===//
192///
193/// ISHeuristic command line option for instruction schedulers.
194///
195//===---------------------------------------------------------------------===//
198ISHeuristic("pre-RA-sched",
200 cl::desc("Instruction schedulers available (before register"
201 " allocation):"));
202
204defaultListDAGScheduler("default", "Best scheduler for the target",
206
207namespace llvm {
208
209 //===--------------------------------------------------------------------===//
210 /// This class is used by SelectionDAGISel to temporarily override
211 /// the optimization level on a per-function basis.
214 CodeGenOptLevel SavedOptLevel;
215 bool SavedFastISel;
216
217 public:
219 : IS(ISel) {
220 SavedOptLevel = IS.OptLevel;
221 SavedFastISel = IS.TM.Options.EnableFastISel;
222 if (NewOptLevel == SavedOptLevel)
223 return;
224 IS.OptLevel = NewOptLevel;
225 IS.TM.setOptLevel(NewOptLevel);
226 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
227 << IS.MF->getFunction().getName() << "\n");
228 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(SavedOptLevel) << " ; After: -O"
229 << static_cast<int>(NewOptLevel) << "\n");
230 if (NewOptLevel == CodeGenOptLevel::None) {
233 dbgs() << "\tFastISel is "
234 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
235 << "\n");
236 }
237 }
238
240 if (IS.OptLevel == SavedOptLevel)
241 return;
242 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
243 << IS.MF->getFunction().getName() << "\n");
244 LLVM_DEBUG(dbgs() << "\tBefore: -O" << static_cast<int>(IS.OptLevel)
245 << " ; After: -O" << static_cast<int>(SavedOptLevel) << "\n");
246 IS.OptLevel = SavedOptLevel;
247 IS.TM.setOptLevel(SavedOptLevel);
248 IS.TM.setFastISel(SavedFastISel);
249 }
250 };
251
252 //===--------------------------------------------------------------------===//
253 /// createDefaultScheduler - This creates an instruction scheduler appropriate
254 /// for the target.
256 CodeGenOptLevel OptLevel) {
257 const TargetLowering *TLI = IS->TLI;
258 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
259
260 // Try first to see if the Target has its own way of selecting a scheduler
261 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
262 return SchedulerCtor(IS, OptLevel);
263 }
264
265 if (OptLevel == CodeGenOptLevel::None ||
266 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
268 return createSourceListDAGScheduler(IS, OptLevel);
270 return createBURRListDAGScheduler(IS, OptLevel);
272 return createHybridListDAGScheduler(IS, OptLevel);
274 return createVLIWDAGScheduler(IS, OptLevel);
276 return createFastDAGScheduler(IS, OptLevel);
278 return createDAGLinearizer(IS, OptLevel);
280 "Unknown sched type!");
281 return createILPListDAGScheduler(IS, OptLevel);
282 }
283
284} // end namespace llvm
285
286// EmitInstrWithCustomInserter - This method should be implemented by targets
287// that mark instructions with the 'usesCustomInserter' flag. These
288// instructions are special in various ways, which require special support to
289// insert. The specified MachineInstr is created but not inserted into any
290// basic blocks, and this method is called to expand it into a sequence of
291// instructions, potentially also creating new basic blocks and control flow.
292// When new basic blocks are inserted and the edges from MBB to its successors
293// are modified, the method should insert pairs of <OldSucc, NewSucc> into the
294// DenseMap.
297 MachineBasicBlock *MBB) const {
298#ifndef NDEBUG
299 dbgs() << "If a target marks an instruction with "
300 "'usesCustomInserter', it must implement "
301 "TargetLowering::EmitInstrWithCustomInserter!\n";
302#endif
303 llvm_unreachable(nullptr);
304}
305
307 SDNode *Node) const {
308 assert(!MI.hasPostISelHook() &&
309 "If a target marks an instruction with 'hasPostISelHook', "
310 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
311}
312
313//===----------------------------------------------------------------------===//
314// SelectionDAGISel code
315//===----------------------------------------------------------------------===//
316
319 : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()),
320 SwiftError(new SwiftErrorValueTracking()),
321 CurDAG(new SelectionDAG(tm, OL)),
322 SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
323 OL)),
324 OptLevel(OL) {
330}
331
333 delete CurDAG;
334 delete SwiftError;
335}
336
349 // AssignmentTrackingAnalysis only runs if assignment tracking is enabled for
350 // the module.
356}
357
358static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
359 MachineModuleInfo &MMI) {
360 // Only needed for MSVC
361 if (!TT.isWindowsMSVCEnvironment())
362 return;
363
364 // If it's already set, nothing to do.
365 if (MMI.usesMSVCFloatingPoint())
366 return;
367
368 for (const Instruction &I : instructions(F)) {
369 if (I.getType()->isFPOrFPVectorTy()) {
370 MMI.setUsesMSVCFloatingPoint(true);
371 return;
372 }
373 for (const auto &Op : I.operands()) {
374 if (Op->getType()->isFPOrFPVectorTy()) {
375 MMI.setUsesMSVCFloatingPoint(true);
376 return;
377 }
378 }
379 }
380}
381
383 // If we already selected that function, we do not need to run SDISel.
384 if (mf.getProperties().hasProperty(
386 return false;
387 // Do some sanity-checking on the command-line options.
389 "-fast-isel-abort > 0 requires -fast-isel");
390
391 const Function &Fn = mf.getFunction();
392 MF = &mf;
393
394 // Decide what flavour of variable location debug-info will be used, before
395 // we change the optimisation level.
396 bool InstrRef = mf.shouldUseDebugInstrRef();
397 mf.setUseDebugInstrRef(InstrRef);
398
399 // Reset the target options before resetting the optimization
400 // level below.
401 // FIXME: This is a horrible hack and should be processed via
402 // codegen looking at the optimization level explicitly when
403 // it wants to look at it.
405 // Reset OptLevel to None for optnone functions.
406 CodeGenOptLevel NewOptLevel = OptLevel;
408 NewOptLevel = CodeGenOptLevel::None;
409 OptLevelChanger OLC(*this, NewOptLevel);
410
413 RegInfo = &MF->getRegInfo();
414 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
415 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
416 ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
417 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(mf.getFunction());
418 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
419 BlockFrequencyInfo *BFI = nullptr;
420 if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOptLevel::None)
421 BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
422
423 FunctionVarLocs const *FnVarLocs = nullptr;
425 FnVarLocs = getAnalysis<AssignmentTrackingAnalysis>().getResults();
426
427 LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
428
429 UniformityInfo *UA = nullptr;
430 if (auto *UAPass = getAnalysisIfAvailable<UniformityInfoWrapperPass>())
431 UA = &UAPass->getUniformityInfo();
432 CurDAG->init(*MF, *ORE, this, LibInfo, UA, PSI, BFI, FnVarLocs);
433 FuncInfo->set(Fn, *MF, CurDAG);
435
436 // Now get the optional analyzes if we want to.
437 // This is based on the possibly changed OptLevel (after optnone is taken
438 // into account). That's unfortunate but OK because it just means we won't
439 // ask for passes that have been required anyway.
440
442 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
443 else
444 FuncInfo->BPI = nullptr;
445
447 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
448 else
449 AA = nullptr;
450
451 SDB->init(GFI, AA, AC, LibInfo);
452
453 MF->setHasInlineAsm(false);
454
455 FuncInfo->SplitCSR = false;
456
457 // We split CSR if the target supports it for the given function
458 // and the function has only return exits.
460 FuncInfo->SplitCSR = true;
461
462 // Collect all the return blocks.
463 for (const BasicBlock &BB : Fn) {
464 if (!succ_empty(&BB))
465 continue;
466
467 const Instruction *Term = BB.getTerminator();
468 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
469 continue;
470
471 // Bail out if the exit block is not Return nor Unreachable.
472 FuncInfo->SplitCSR = false;
473 break;
474 }
475 }
476
477 MachineBasicBlock *EntryMBB = &MF->front();
478 if (FuncInfo->SplitCSR)
479 // This performs initialization so lowering for SplitCSR will be correct.
480 TLI->initializeSplitCSR(EntryMBB);
481
482 SelectAllBasicBlocks(Fn);
484 DiagnosticInfoISelFallback DiagFallback(Fn);
485 Fn.getContext().diagnose(DiagFallback);
486 }
487
488 // Replace forward-declared registers with the registers containing
489 // the desired value.
490 // Note: it is important that this happens **before** the call to
491 // EmitLiveInCopies, since implementations can skip copies of unused
492 // registers. If we don't apply the reg fixups before, some registers may
493 // appear as unused and will be skipped, resulting in bad MI.
495 for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
496 E = FuncInfo->RegFixups.end();
497 I != E; ++I) {
498 Register From = I->first;
499 Register To = I->second;
500 // If To is also scheduled to be replaced, find what its ultimate
501 // replacement is.
502 while (true) {
503 DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
504 if (J == E)
505 break;
506 To = J->second;
507 }
508 // Make sure the new register has a sufficiently constrained register class.
509 if (From.isVirtual() && To.isVirtual())
510 MRI.constrainRegClass(To, MRI.getRegClass(From));
511 // Replace it.
512
513 // Replacing one register with another won't touch the kill flags.
514 // We need to conservatively clear the kill flags as a kill on the old
515 // register might dominate existing uses of the new register.
516 if (!MRI.use_empty(To))
517 MRI.clearKillFlags(From);
518 MRI.replaceRegWith(From, To);
519 }
520
521 // If the first basic block in the function has live ins that need to be
522 // copied into vregs, emit the copies into the top of the block before
523 // emitting the code for the block.
525 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
526
527 // Insert copies in the entry block and the return blocks.
528 if (FuncInfo->SplitCSR) {
530 // Collect all the return blocks.
531 for (MachineBasicBlock &MBB : mf) {
532 if (!MBB.succ_empty())
533 continue;
534
536 if (Term != MBB.end() && Term->isReturn()) {
537 Returns.push_back(&MBB);
538 continue;
539 }
540 }
541 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
542 }
543
545 if (!FuncInfo->ArgDbgValues.empty())
546 for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
547 if (LI.second)
548 LiveInMap.insert(LI);
549
550 // Insert DBG_VALUE instructions for function arguments to the entry block.
551 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
552 MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
553 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
554 "Function parameters should not be described by DBG_VALUE_LIST.");
555 bool hasFI = MI->getDebugOperand(0).isFI();
556 Register Reg =
557 hasFI ? TRI.getFrameRegister(*MF) : MI->getDebugOperand(0).getReg();
558 if (Reg.isPhysical())
559 EntryMBB->insert(EntryMBB->begin(), MI);
560 else {
561 MachineInstr *Def = RegInfo->getVRegDef(Reg);
562 if (Def) {
563 MachineBasicBlock::iterator InsertPos = Def;
564 // FIXME: VR def may not be in entry block.
565 Def->getParent()->insert(std::next(InsertPos), MI);
566 } else
567 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
568 << Register::virtReg2Index(Reg) << "\n");
569 }
570
571 // Don't try and extend through copies in instruction referencing mode.
572 if (InstrRef)
573 continue;
574
575 // If Reg is live-in then update debug info to track its copy in a vreg.
576 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
577 if (LDI != LiveInMap.end()) {
578 assert(!hasFI && "There's no handling of frame pointer updating here yet "
579 "- add if needed");
580 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
581 MachineBasicBlock::iterator InsertPos = Def;
582 const MDNode *Variable = MI->getDebugVariable();
583 const MDNode *Expr = MI->getDebugExpression();
584 DebugLoc DL = MI->getDebugLoc();
585 bool IsIndirect = MI->isIndirectDebugValue();
586 if (IsIndirect)
587 assert(MI->getDebugOffset().getImm() == 0 &&
588 "DBG_VALUE with nonzero offset");
589 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
590 "Expected inlined-at fields to agree");
591 assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
592 "Didn't expect to see a DBG_VALUE_LIST here");
593 // Def is never a terminator here, so it is ok to increment InsertPos.
594 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
595 IsIndirect, LDI->second, Variable, Expr);
596
597 // If this vreg is directly copied into an exported register then
598 // that COPY instructions also need DBG_VALUE, if it is the only
599 // user of LDI->second.
600 MachineInstr *CopyUseMI = nullptr;
602 UI = RegInfo->use_instr_begin(LDI->second),
603 E = RegInfo->use_instr_end(); UI != E; ) {
604 MachineInstr *UseMI = &*(UI++);
605 if (UseMI->isDebugValue()) continue;
606 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
607 CopyUseMI = UseMI; continue;
608 }
609 // Otherwise this is another use or second copy use.
610 CopyUseMI = nullptr; break;
611 }
612 if (CopyUseMI &&
613 TRI.getRegSizeInBits(LDI->second, MRI) ==
614 TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
615 // Use MI's debug location, which describes where Variable was
616 // declared, rather than whatever is attached to CopyUseMI.
617 MachineInstr *NewMI =
618 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
619 CopyUseMI->getOperand(0).getReg(), Variable, Expr);
620 MachineBasicBlock::iterator Pos = CopyUseMI;
621 EntryMBB->insertAfter(Pos, NewMI);
622 }
623 }
624 }
625
626 // For debug-info, in instruction referencing mode, we need to perform some
627 // post-isel maintenence.
628 if (MF->useDebugInstrRef())
630
631 // Determine if there are any calls in this machine function.
633 for (const auto &MBB : *MF) {
634 if (MFI.hasCalls() && MF->hasInlineAsm())
635 break;
636
637 for (const auto &MI : MBB) {
638 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
639 if ((MCID.isCall() && !MCID.isReturn()) ||
640 MI.isStackAligningInlineAsm()) {
641 MFI.setHasCalls(true);
642 }
643 if (MI.isInlineAsm()) {
644 MF->setHasInlineAsm(true);
645 }
646 }
647 }
648
649 // Determine if there is a call to setjmp in the machine function.
651
652 // Determine if floating point is used for msvc
654
655 // Release function-specific state. SDB and CurDAG are already cleared
656 // at this point.
657 FuncInfo->clear();
658
659 LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
660 LLVM_DEBUG(MF->print(dbgs()));
661
662 return true;
663}
664
668 bool ShouldAbort) {
669 // Print the function name explicitly if we don't have a debug location (which
670 // makes the diagnostic less useful) or if we're going to emit a raw error.
671 if (!R.getLocation().isValid() || ShouldAbort)
672 R << (" (in function: " + MF.getName() + ")").str();
673
674 if (ShouldAbort)
675 report_fatal_error(Twine(R.getMsg()));
676
677 ORE.emit(R);
678 LLVM_DEBUG(dbgs() << R.getMsg() << "\n");
679}
680
681void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
683 bool &HadTailCall) {
684 // Allow creating illegal types during DAG building for the basic block.
686
687 // Lower the instructions. If a call is emitted as a tail call, cease emitting
688 // nodes for this block.
689 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
690 if (!ElidedArgCopyInstrs.count(&*I))
691 SDB->visit(*I);
692 }
693
694 // Make sure the root of the DAG is up-to-date.
695 CurDAG->setRoot(SDB->getControlRoot());
696 HadTailCall = SDB->HasTailCall;
697 SDB->resolveOrClearDbgInfo();
698 SDB->clear();
699
700 // Final step, emit the lowered DAG as machine code.
701 CodeGenAndEmitDAG();
702}
703
704void SelectionDAGISel::ComputeLiveOutVRegInfo() {
707
708 Worklist.push_back(CurDAG->getRoot().getNode());
709 Added.insert(CurDAG->getRoot().getNode());
710
711 KnownBits Known;
712
713 do {
714 SDNode *N = Worklist.pop_back_val();
715
716 // Otherwise, add all chain operands to the worklist.
717 for (const SDValue &Op : N->op_values())
718 if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
719 Worklist.push_back(Op.getNode());
720
721 // If this is a CopyToReg with a vreg dest, process it.
722 if (N->getOpcode() != ISD::CopyToReg)
723 continue;
724
725 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
726 if (!Register::isVirtualRegister(DestReg))
727 continue;
728
729 // Ignore non-integer values.
730 SDValue Src = N->getOperand(2);
731 EVT SrcVT = Src.getValueType();
732 if (!SrcVT.isInteger())
733 continue;
734
735 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
736 Known = CurDAG->computeKnownBits(Src);
737 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
738 } while (!Worklist.empty());
739}
740
741void SelectionDAGISel::CodeGenAndEmitDAG() {
742 StringRef GroupName = "sdag";
743 StringRef GroupDescription = "Instruction Selection and Scheduling";
744 std::string BlockName;
745 bool MatchFilterBB = false; (void)MatchFilterBB;
746#ifndef NDEBUG
748 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn);
749#endif
750
751 // Pre-type legalization allow creation of any node types.
753
754#ifndef NDEBUG
755 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
757 FuncInfo->MBB->getBasicBlock()->getName());
758#endif
759#ifdef NDEBUG
763#endif
764 {
765 BlockName =
766 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
767 }
768 LLVM_DEBUG(dbgs() << "Initial selection DAG: "
769 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
770 << "'\n";
771 CurDAG->dump());
772
773#ifndef NDEBUG
776#endif
777
778 if (ViewDAGCombine1 && MatchFilterBB)
779 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
780
781 // Run the DAG combiner in pre-legalize mode.
782 {
783 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
784 GroupDescription, TimePassesIsEnabled);
786 }
787
788 LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
789 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
790 << "'\n";
791 CurDAG->dump());
792
793#ifndef NDEBUG
796#endif
797
798 // Second step, hack on the DAG until it only uses operations and types that
799 // the target supports.
800 if (ViewLegalizeTypesDAGs && MatchFilterBB)
801 CurDAG->viewGraph("legalize-types input for " + BlockName);
802
803 bool Changed;
804 {
805 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
806 GroupDescription, TimePassesIsEnabled);
807 Changed = CurDAG->LegalizeTypes();
808 }
809
810 LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
811 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
812 << "'\n";
813 CurDAG->dump());
814
815#ifndef NDEBUG
818#endif
819
820 // Only allow creation of legal node types.
822
823 if (Changed) {
824 if (ViewDAGCombineLT && MatchFilterBB)
825 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
826
827 // Run the DAG combiner in post-type-legalize mode.
828 {
829 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
830 GroupName, GroupDescription, TimePassesIsEnabled);
832 }
833
834 LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
835 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
836 << "'\n";
837 CurDAG->dump());
838
839#ifndef NDEBUG
842#endif
843 }
844
845 {
846 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
847 GroupDescription, TimePassesIsEnabled);
848 Changed = CurDAG->LegalizeVectors();
849 }
850
851 if (Changed) {
852 LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
853 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
854 << "'\n";
855 CurDAG->dump());
856
857#ifndef NDEBUG
860#endif
861
862 {
863 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
864 GroupDescription, TimePassesIsEnabled);
866 }
867
868 LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
869 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
870 << "'\n";
871 CurDAG->dump());
872
873#ifndef NDEBUG
876#endif
877
878 if (ViewDAGCombineLT && MatchFilterBB)
879 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
880
881 // Run the DAG combiner in post-type-legalize mode.
882 {
883 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
884 GroupName, GroupDescription, TimePassesIsEnabled);
886 }
887
888 LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
889 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
890 << "'\n";
891 CurDAG->dump());
892
893#ifndef NDEBUG
896#endif
897 }
898
899 if (ViewLegalizeDAGs && MatchFilterBB)
900 CurDAG->viewGraph("legalize input for " + BlockName);
901
902 {
903 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
904 GroupDescription, TimePassesIsEnabled);
905 CurDAG->Legalize();
906 }
907
908 LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
909 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
910 << "'\n";
911 CurDAG->dump());
912
913#ifndef NDEBUG
916#endif
917
918 if (ViewDAGCombine2 && MatchFilterBB)
919 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
920
921 // Run the DAG combiner in post-legalize mode.
922 {
923 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
924 GroupDescription, TimePassesIsEnabled);
926 }
927
928 LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
929 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
930 << "'\n";
931 CurDAG->dump());
932
933#ifndef NDEBUG
936#endif
937
939 ComputeLiveOutVRegInfo();
940
941 if (ViewISelDAGs && MatchFilterBB)
942 CurDAG->viewGraph("isel input for " + BlockName);
943
944 // Third, instruction select all of the operations to machine code, adding the
945 // code to the MachineBasicBlock.
946 {
947 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
948 GroupDescription, TimePassesIsEnabled);
949 DoInstructionSelection();
950 }
951
952 LLVM_DEBUG(dbgs() << "Selected selection DAG: "
953 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
954 << "'\n";
955 CurDAG->dump());
956
957 if (ViewSchedDAGs && MatchFilterBB)
958 CurDAG->viewGraph("scheduler input for " + BlockName);
959
960 // Schedule machine code.
961 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
962 {
963 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
964 GroupDescription, TimePassesIsEnabled);
965 Scheduler->Run(CurDAG, FuncInfo->MBB);
966 }
967
968 if (ViewSUnitDAGs && MatchFilterBB)
969 Scheduler->viewGraph();
970
971 // Emit machine code to BB. This can change 'BB' to the last block being
972 // inserted into.
973 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
974 {
975 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
976 GroupDescription, TimePassesIsEnabled);
977
978 // FuncInfo->InsertPt is passed by reference and set to the end of the
979 // scheduled instructions.
980 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
981 }
982
983 // If the block was split, make sure we update any references that are used to
984 // update PHI nodes later on.
985 if (FirstMBB != LastMBB)
986 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
987
988 // Free the scheduler state.
989 {
990 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
991 GroupDescription, TimePassesIsEnabled);
992 delete Scheduler;
993 }
994
995 // Free the SelectionDAG state, now that we're finished with it.
996 CurDAG->clear();
997}
998
999namespace {
1000
1001/// ISelUpdater - helper class to handle updates of the instruction selection
1002/// graph.
1003class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1004 SelectionDAG::allnodes_iterator &ISelPosition;
1005
1006public:
1007 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1008 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1009
1010 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1011 /// deleted is the current ISelPosition node, update ISelPosition.
1012 ///
1013 void NodeDeleted(SDNode *N, SDNode *E) override {
1014 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1015 ++ISelPosition;
1016 }
1017
1018 /// NodeInserted - Handle new nodes inserted into the graph: propagate
1019 /// metadata from root nodes that also applies to new nodes, in case the root
1020 /// is later deleted.
1021 void NodeInserted(SDNode *N) override {
1022 SDNode *CurNode = &*ISelPosition;
1023 if (MDNode *MD = DAG.getPCSections(CurNode))
1024 DAG.addPCSections(N, MD);
1025 }
1026};
1027
1028} // end anonymous namespace
1029
1030// This function is used to enforce the topological node id property
1031// leveraged during instruction selection. Before the selection process all
1032// nodes are given a non-negative id such that all nodes have a greater id than
1033// their operands. As this holds transitively we can prune checks that a node N
1034// is a predecessor of M another by not recursively checking through M's
1035// operands if N's ID is larger than M's ID. This significantly improves
1036// performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
1037
1038// However, when we fuse multiple nodes into a single node during the
1039// selection we may induce a predecessor relationship between inputs and
1040// outputs of distinct nodes being merged, violating the topological property.
1041// Should a fused node have a successor which has yet to be selected,
1042// our legality checks would be incorrect. To avoid this we mark all unselected
1043// successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
1044// (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1045// We use bit-negation to more clearly enforce that node id -1 can only be
1046// achieved by selected nodes. As the conversion is reversable to the original
1047// Id, topological pruning can still be leveraged when looking for unselected
1048// nodes. This method is called internally in all ISel replacement related
1049// functions.
1052 Nodes.push_back(Node);
1053
1054 while (!Nodes.empty()) {
1055 SDNode *N = Nodes.pop_back_val();
1056 for (auto *U : N->uses()) {
1057 auto UId = U->getNodeId();
1058 if (UId > 0) {
1060 Nodes.push_back(U);
1061 }
1062 }
1063 }
1064}
1065
1066// InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
1067// NodeId with the equivalent node id which is invalid for topological
1068// pruning.
1070 int InvalidId = -(N->getNodeId() + 1);
1071 N->setNodeId(InvalidId);
1072}
1073
1074// getUninvalidatedNodeId - get original uninvalidated node id.
1076 int Id = N->getNodeId();
1077 if (Id < -1)
1078 return -(Id + 1);
1079 return Id;
1080}
1081
1082void SelectionDAGISel::DoInstructionSelection() {
1083 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1084 << printMBBReference(*FuncInfo->MBB) << " '"
1085 << FuncInfo->MBB->getName() << "'\n");
1086
1088
1089 // Select target instructions for the DAG.
1090 {
1091 // Number all nodes with a topological order and set DAGSize.
1093
1094 // Create a dummy node (which is not added to allnodes), that adds
1095 // a reference to the root node, preventing it from being deleted,
1096 // and tracking any changes of the root.
1097 HandleSDNode Dummy(CurDAG->getRoot());
1099 ++ISelPosition;
1100
1101 // Make sure that ISelPosition gets properly updated when nodes are deleted
1102 // in calls made from this function. New nodes inherit relevant metadata.
1103 ISelUpdater ISU(*CurDAG, ISelPosition);
1104
1105 // The AllNodes list is now topological-sorted. Visit the
1106 // nodes by starting at the end of the list (the root of the
1107 // graph) and preceding back toward the beginning (the entry
1108 // node).
1109 while (ISelPosition != CurDAG->allnodes_begin()) {
1110 SDNode *Node = &*--ISelPosition;
1111 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1112 // but there are currently some corner cases that it misses. Also, this
1113 // makes it theoretically possible to disable the DAGCombiner.
1114 if (Node->use_empty())
1115 continue;
1116
1117#ifndef NDEBUG
1119 Nodes.push_back(Node);
1120
1121 while (!Nodes.empty()) {
1122 auto N = Nodes.pop_back_val();
1123 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1124 continue;
1125 for (const SDValue &Op : N->op_values()) {
1126 if (Op->getOpcode() == ISD::TokenFactor)
1127 Nodes.push_back(Op.getNode());
1128 else {
1129 // We rely on topological ordering of node ids for checking for
1130 // cycles when fusing nodes during selection. All unselected nodes
1131 // successors of an already selected node should have a negative id.
1132 // This assertion will catch such cases. If this assertion triggers
1133 // it is likely you using DAG-level Value/Node replacement functions
1134 // (versus equivalent ISEL replacement) in backend-specific
1135 // selections. See comment in EnforceNodeIdInvariant for more
1136 // details.
1137 assert(Op->getNodeId() != -1 &&
1138 "Node has already selected predecessor node");
1139 }
1140 }
1141 }
1142#endif
1143
1144 // When we are using non-default rounding modes or FP exception behavior
1145 // FP operations are represented by StrictFP pseudo-operations. For
1146 // targets that do not (yet) understand strict FP operations directly,
1147 // we convert them to normal FP opcodes instead at this point. This
1148 // will allow them to be handled by existing target-specific instruction
1149 // selectors.
1150 if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1151 // For some opcodes, we need to call TLI->getOperationAction using
1152 // the first operand type instead of the result type. Note that this
1153 // must match what SelectionDAGLegalize::LegalizeOp is doing.
1154 EVT ActionVT;
1155 switch (Node->getOpcode()) {
1158 case ISD::STRICT_LRINT:
1159 case ISD::STRICT_LLRINT:
1160 case ISD::STRICT_LROUND:
1162 case ISD::STRICT_FSETCC:
1164 ActionVT = Node->getOperand(1).getValueType();
1165 break;
1166 default:
1167 ActionVT = Node->getValueType(0);
1168 break;
1169 }
1170 if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1173 }
1174
1175 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1176 Node->dump(CurDAG));
1177
1178 Select(Node);
1179 }
1180
1181 CurDAG->setRoot(Dummy.getValue());
1182 }
1183
1184 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1185
1187}
1188
1190 for (const User *U : CPI->users()) {
1191 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1192 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1193 if (IID == Intrinsic::eh_exceptionpointer ||
1194 IID == Intrinsic::eh_exceptioncode)
1195 return true;
1196 }
1197 }
1198 return false;
1199}
1200
1201// wasm.landingpad.index intrinsic is for associating a landing pad index number
1202// with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1203// and store the mapping in the function.
1205 const CatchPadInst *CPI) {
1206 MachineFunction *MF = MBB->getParent();
1207 // In case of single catch (...), we don't emit LSDA, so we don't need
1208 // this information.
1209 bool IsSingleCatchAllClause =
1210 CPI->arg_size() == 1 &&
1211 cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1212 // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
1213 // and they don't need LSDA info
1214 bool IsCatchLongjmp = CPI->arg_size() == 0;
1215 if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
1216 // Create a mapping from landing pad label to landing pad index.
1217 bool IntrFound = false;
1218 for (const User *U : CPI->users()) {
1219 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1220 Intrinsic::ID IID = Call->getIntrinsicID();
1221 if (IID == Intrinsic::wasm_landingpad_index) {
1222 Value *IndexArg = Call->getArgOperand(1);
1223 int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1225 IntrFound = true;
1226 break;
1227 }
1228 }
1229 }
1230 assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1231 (void)IntrFound;
1232 }
1233}
1234
1235/// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1236/// do other setup for EH landing-pad blocks.
1237bool SelectionDAGISel::PrepareEHLandingPad() {
1239 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1240 const BasicBlock *LLVMBB = MBB->getBasicBlock();
1241 const TargetRegisterClass *PtrRC =
1243
1244 auto Pers = classifyEHPersonality(PersonalityFn);
1245
1246 // Catchpads have one live-in register, which typically holds the exception
1247 // pointer or code.
1248 if (isFuncletEHPersonality(Pers)) {
1249 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1251 // Get or create the virtual register to hold the pointer or code. Mark
1252 // the live in physreg and copy into the vreg.
1253 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1254 assert(EHPhysReg && "target lacks exception pointer register");
1255 MBB->addLiveIn(EHPhysReg);
1256 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1257 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1258 TII->get(TargetOpcode::COPY), VReg)
1259 .addReg(EHPhysReg, RegState::Kill);
1260 }
1261 }
1262 return true;
1263 }
1264
1265 // Add a label to mark the beginning of the landing pad. Deletion of the
1266 // landing pad can thus be detected via the MachineModuleInfo.
1268
1269 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1270 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1271 .addSym(Label);
1272
1273 // If the unwinder does not preserve all registers, ensure that the
1274 // function marks the clobbered registers as used.
1276 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1278
1279 if (Pers == EHPersonality::Wasm_CXX) {
1280 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
1282 } else {
1283 // Assign the call site to the landing pad's begin label.
1284 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1285 // Mark exception register as live in.
1286 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1287 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1288 // Mark exception selector register as live in.
1289 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1290 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1291 }
1292
1293 return true;
1294}
1295
1296// Mark and Report IPToState for each Block under IsEHa
1297void SelectionDAGISel::reportIPToStateForBlocks(MachineFunction *MF) {
1298 MachineModuleInfo &MMI = MF->getMMI();
1300 if (!EHInfo)
1301 return;
1302 for (auto MBBI = MF->begin(), E = MF->end(); MBBI != E; ++MBBI) {
1304 const BasicBlock *BB = MBB->getBasicBlock();
1305 int State = EHInfo->BlockToStateMap[BB];
1306 if (BB->getFirstMayFaultInst()) {
1307 // Report IP range only for blocks with Faulty inst
1308 auto MBBb = MBB->getFirstNonPHI();
1309 MachineInstr *MIb = &*MBBb;
1310 if (MIb->isTerminator())
1311 continue;
1312
1313 // Insert EH Labels
1314 MCSymbol *BeginLabel = MMI.getContext().createTempSymbol();
1315 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
1316 EHInfo->addIPToStateRange(State, BeginLabel, EndLabel);
1317 BuildMI(*MBB, MBBb, SDB->getCurDebugLoc(),
1318 TII->get(TargetOpcode::EH_LABEL))
1319 .addSym(BeginLabel);
1320 auto MBBe = MBB->instr_end();
1321 MachineInstr *MIe = &*(--MBBe);
1322 // insert before (possible multiple) terminators
1323 while (MIe->isTerminator())
1324 MIe = &*(--MBBe);
1325 ++MBBe;
1326 BuildMI(*MBB, MBBe, SDB->getCurDebugLoc(),
1327 TII->get(TargetOpcode::EH_LABEL))
1328 .addSym(EndLabel);
1329 }
1330 }
1331}
1332
1333/// isFoldedOrDeadInstruction - Return true if the specified instruction is
1334/// side-effect free and is either dead or folded into a generated instruction.
1335/// Return false if it needs to be emitted.
1337 const FunctionLoweringInfo &FuncInfo) {
1338 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1339 !I->isTerminator() && // Terminators aren't folded.
1340 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1341 !I->isEHPad() && // EH pad instructions aren't folded.
1342 !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1343}
1344
1346 const Value *Arg, DIExpression *Expr,
1347 DILocalVariable *Var,
1348 DebugLoc DbgLoc) {
1349 if (!Expr->isEntryValue() || !isa<Argument>(Arg))
1350 return false;
1351
1352 auto ArgIt = FuncInfo.ValueMap.find(Arg);
1353 if (ArgIt == FuncInfo.ValueMap.end())
1354 return false;
1355 Register ArgVReg = ArgIt->getSecond();
1356
1357 // Find the corresponding livein physical register to this argument.
1358 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1359 if (VirtReg == ArgVReg) {
1360 // Append an op deref to account for the fact that this is a dbg_declare.
1361 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
1362 FuncInfo.MF->setVariableDbgInfo(Var, Expr, PhysReg, DbgLoc);
1363 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1364 << ", Expr=" << *Expr << ", MCRegister=" << PhysReg
1365 << ", DbgLoc=" << DbgLoc << "\n");
1366 return true;
1367 }
1368 return false;
1369}
1370
1372 const Value *Address, DIExpression *Expr,
1373 DILocalVariable *Var, DebugLoc DbgLoc) {
1374 if (!Address) {
1375 LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *Var
1376 << " (bad address)\n");
1377 return false;
1378 }
1379
1380 if (processIfEntryValueDbgDeclare(FuncInfo, Address, Expr, Var, DbgLoc))
1381 return true;
1382
1383 MachineFunction *MF = FuncInfo.MF;
1384 const DataLayout &DL = MF->getDataLayout();
1385
1386 assert(Var && "Missing variable");
1387 assert(DbgLoc && "Missing location");
1388
1389 // Look through casts and constant offset GEPs. These mostly come from
1390 // inalloca.
1391 APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
1392 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1393
1394 // Check if the variable is a static alloca or a byval or inalloca
1395 // argument passed in memory. If it is not, then we will ignore this
1396 // intrinsic and handle this during isel like dbg.value.
1397 int FI = std::numeric_limits<int>::max();
1398 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1399 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1400 if (SI != FuncInfo.StaticAllocaMap.end())
1401 FI = SI->second;
1402 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1403 FI = FuncInfo.getArgumentFrameIndex(Arg);
1404
1405 if (FI == std::numeric_limits<int>::max())
1406 return false;
1407
1408 if (Offset.getBoolValue())
1410 Offset.getZExtValue());
1411
1412 LLVM_DEBUG(dbgs() << "processDbgDeclare: setVariableDbgInfo Var=" << *Var
1413 << ", Expr=" << *Expr << ", FI=" << FI
1414 << ", DbgLoc=" << DbgLoc << "\n");
1415 MF->setVariableDbgInfo(Var, Expr, FI, DbgLoc);
1416 return true;
1417}
1418
1419/// Collect llvm.dbg.declare information. This is done after argument lowering
1420/// in case the declarations refer to arguments.
1422 for (const auto &I : instructions(*FuncInfo.Fn)) {
1423 const auto *DI = dyn_cast<DbgDeclareInst>(&I);
1424 if (DI && processDbgDeclare(FuncInfo, DI->getAddress(), DI->getExpression(),
1425 DI->getVariable(), DI->getDebugLoc()))
1426 FuncInfo.PreprocessedDbgDeclares.insert(DI);
1427 }
1428}
1429
1430/// Collect single location variable information generated with assignment
1431/// tracking. This is done after argument lowering in case the declarations
1432/// refer to arguments.
1434 FunctionVarLocs const *FnVarLocs) {
1435 for (auto It = FnVarLocs->single_locs_begin(),
1436 End = FnVarLocs->single_locs_end();
1437 It != End; ++It) {
1438 assert(!It->Values.hasArgList() && "Single loc variadic ops not supported");
1439 processDbgDeclare(FuncInfo, It->Values.getVariableLocationOp(0), It->Expr,
1440 FnVarLocs->getDILocalVariable(It->VariableID), It->DL);
1441 }
1442}
1443
1444void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1445 FastISelFailed = false;
1446 // Initialize the Fast-ISel state, if needed.
1447 FastISel *FastIS = nullptr;
1449 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1450 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1451 }
1452
1454
1455 // Lower arguments up front. An RPO iteration always visits the entry block
1456 // first.
1457 assert(*RPOT.begin() == &Fn.getEntryBlock());
1458 ++NumEntryBlocks;
1459
1460 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1461 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1462 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1463
1465
1466 if (!FastIS) {
1467 LowerArguments(Fn);
1468 } else {
1469 // See if fast isel can lower the arguments.
1470 FastIS->startNewBlock();
1471 if (!FastIS->lowerArguments()) {
1472 FastISelFailed = true;
1473 // Fast isel failed to lower these arguments
1474 ++NumFastIselFailLowerArguments;
1475
1476 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1477 Fn.getSubprogram(),
1478 &Fn.getEntryBlock());
1479 R << "FastISel didn't lower all arguments: "
1480 << ore::NV("Prototype", Fn.getFunctionType());
1482
1483 // Use SelectionDAG argument lowering
1484 LowerArguments(Fn);
1485 CurDAG->setRoot(SDB->getControlRoot());
1486 SDB->clear();
1487 CodeGenAndEmitDAG();
1488 }
1489
1490 // If we inserted any instructions at the beginning, make a note of
1491 // where they are, so we can be sure to emit subsequent instructions
1492 // after them.
1493 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1494 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1495 else
1496 FastIS->setLastLocalValue(nullptr);
1497 }
1498
1499 bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1500
1501 if (FastIS && Inserted)
1502 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1503
1506 "expected AssignmentTrackingAnalysis pass results");
1508 } else {
1510 }
1511
1512 // Iterate over all basic blocks in the function.
1513 StackProtector &SP = getAnalysis<StackProtector>();
1514 for (const BasicBlock *LLVMBB : RPOT) {
1516 bool AllPredsVisited = true;
1517 for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1518 if (!FuncInfo->VisitedBBs.count(Pred)) {
1519 AllPredsVisited = false;
1520 break;
1521 }
1522 }
1523
1524 if (AllPredsVisited) {
1525 for (const PHINode &PN : LLVMBB->phis())
1526 FuncInfo->ComputePHILiveOutRegInfo(&PN);
1527 } else {
1528 for (const PHINode &PN : LLVMBB->phis())
1529 FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1530 }
1531
1532 FuncInfo->VisitedBBs.insert(LLVMBB);
1533 }
1534
1535 BasicBlock::const_iterator const Begin =
1536 LLVMBB->getFirstNonPHI()->getIterator();
1537 BasicBlock::const_iterator const End = LLVMBB->end();
1539
1540 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1541 if (!FuncInfo->MBB)
1542 continue; // Some blocks like catchpads have no code or MBB.
1543
1544 // Insert new instructions after any phi or argument setup code.
1545 FuncInfo->InsertPt = FuncInfo->MBB->end();
1546
1547 // Setup an EH landing-pad block.
1548 FuncInfo->ExceptionPointerVirtReg = 0;
1549 FuncInfo->ExceptionSelectorVirtReg = 0;
1550 if (LLVMBB->isEHPad())
1551 if (!PrepareEHLandingPad())
1552 continue;
1553
1554 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1555 if (FastIS) {
1556 if (LLVMBB != &Fn.getEntryBlock())
1557 FastIS->startNewBlock();
1558
1559 unsigned NumFastIselRemaining = std::distance(Begin, End);
1560
1561 // Pre-assign swifterror vregs.
1562 SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1563
1564 // Do FastISel on as many instructions as possible.
1565 for (; BI != Begin; --BI) {
1566 const Instruction *Inst = &*std::prev(BI);
1567
1568 // If we no longer require this instruction, skip it.
1569 if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1570 ElidedArgCopyInstrs.count(Inst)) {
1571 --NumFastIselRemaining;
1572 continue;
1573 }
1574
1575 // Bottom-up: reset the insert pos at the top, after any local-value
1576 // instructions.
1577 FastIS->recomputeInsertPt();
1578
1579 // Try to select the instruction with FastISel.
1580 if (FastIS->selectInstruction(Inst)) {
1581 --NumFastIselRemaining;
1582 ++NumFastIselSuccess;
1583 // If fast isel succeeded, skip over all the folded instructions, and
1584 // then see if there is a load right before the selected instructions.
1585 // Try to fold the load if so.
1586 const Instruction *BeforeInst = Inst;
1587 while (BeforeInst != &*Begin) {
1588 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1589 if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1590 break;
1591 }
1592 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1593 BeforeInst->hasOneUse() &&
1594 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1595 // If we succeeded, don't re-select the load.
1597 << "FastISel folded load: " << *BeforeInst << "\n");
1598 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1599 --NumFastIselRemaining;
1600 ++NumFastIselSuccess;
1601 }
1602 continue;
1603 }
1604
1605 FastISelFailed = true;
1606
1607 // Then handle certain instructions as single-LLVM-Instruction blocks.
1608 // We cannot separate out GCrelocates to their own blocks since we need
1609 // to keep track of gc-relocates for a particular gc-statepoint. This is
1610 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1611 // visitGCRelocate.
1612 if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1613 !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1614 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1615 Inst->getDebugLoc(), LLVMBB);
1616
1617 R << "FastISel missed call";
1618
1619 if (R.isEnabled() || EnableFastISelAbort) {
1620 std::string InstStrStorage;
1621 raw_string_ostream InstStr(InstStrStorage);
1622 InstStr << *Inst;
1623
1624 R << ": " << InstStr.str();
1625 }
1626
1628
1629 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1630 !Inst->use_empty()) {
1631 Register &R = FuncInfo->ValueMap[Inst];
1632 if (!R)
1633 R = FuncInfo->CreateRegs(Inst);
1634 }
1635
1636 bool HadTailCall = false;
1637 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1638 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1639
1640 // If the call was emitted as a tail call, we're done with the block.
1641 // We also need to delete any previously emitted instructions.
1642 if (HadTailCall) {
1643 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1644 --BI;
1645 break;
1646 }
1647
1648 // Recompute NumFastIselRemaining as Selection DAG instruction
1649 // selection may have handled the call, input args, etc.
1650 unsigned RemainingNow = std::distance(Begin, BI);
1651 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1652 NumFastIselRemaining = RemainingNow;
1653 continue;
1654 }
1655
1656 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1657 Inst->getDebugLoc(), LLVMBB);
1658
1659 bool ShouldAbort = EnableFastISelAbort;
1660 if (Inst->isTerminator()) {
1661 // Use a different message for terminator misses.
1662 R << "FastISel missed terminator";
1663 // Don't abort for terminator unless the level is really high
1664 ShouldAbort = (EnableFastISelAbort > 2);
1665 } else {
1666 R << "FastISel missed";
1667 }
1668
1669 if (R.isEnabled() || EnableFastISelAbort) {
1670 std::string InstStrStorage;
1671 raw_string_ostream InstStr(InstStrStorage);
1672 InstStr << *Inst;
1673 R << ": " << InstStr.str();
1674 }
1675
1676 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1677
1678 NumFastIselFailures += NumFastIselRemaining;
1679 break;
1680 }
1681
1682 FastIS->recomputeInsertPt();
1683 }
1684
1685 if (SP.shouldEmitSDCheck(*LLVMBB)) {
1686 bool FunctionBasedInstrumentation =
1688 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1689 FunctionBasedInstrumentation);
1690 }
1691
1692 if (Begin != BI)
1693 ++NumDAGBlocks;
1694 else
1695 ++NumFastIselBlocks;
1696
1697 if (Begin != BI) {
1698 // Run SelectionDAG instruction selection on the remainder of the block
1699 // not handled by FastISel. If FastISel is not run, this is the entire
1700 // block.
1701 bool HadTailCall;
1702 SelectBasicBlock(Begin, BI, HadTailCall);
1703
1704 // But if FastISel was run, we already selected some of the block.
1705 // If we emitted a tail-call, we need to delete any previously emitted
1706 // instruction that follows it.
1707 if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1708 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1709 }
1710
1711 if (FastIS)
1712 FastIS->finishBasicBlock();
1713 FinishBasicBlock();
1714 FuncInfo->PHINodesToUpdate.clear();
1715 ElidedArgCopyInstrs.clear();
1716 }
1717
1718 // AsynchEH: Report Block State under -AsynchEH
1719 if (Fn.getParent()->getModuleFlag("eh-asynch"))
1720 reportIPToStateForBlocks(MF);
1721
1723
1725
1726 delete FastIS;
1727 SDB->clearDanglingDebugInfo();
1728 SDB->SPDescriptor.resetPerFunctionState();
1729}
1730
1731void
1732SelectionDAGISel::FinishBasicBlock() {
1733 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1734 << FuncInfo->PHINodesToUpdate.size() << "\n";
1735 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1736 ++i) dbgs()
1737 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1738 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1739
1740 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1741 // PHI nodes in successors.
1742 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1743 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1744 assert(PHI->isPHI() &&
1745 "This is not a machine PHI node that we are updating!");
1746 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1747 continue;
1748 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1749 }
1750
1751 // Handle stack protector.
1752 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1753 // The target provides a guard check function. There is no need to
1754 // generate error handling code or to split current basic block.
1755 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1756
1757 // Add load and check to the basicblock.
1758 FuncInfo->MBB = ParentMBB;
1759 FuncInfo->InsertPt =
1761 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1762 CurDAG->setRoot(SDB->getRoot());
1763 SDB->clear();
1764 CodeGenAndEmitDAG();
1765
1766 // Clear the Per-BB State.
1767 SDB->SPDescriptor.resetPerBBState();
1768 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1769 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1770 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1771
1772 // Find the split point to split the parent mbb. At the same time copy all
1773 // physical registers used in the tail of parent mbb into virtual registers
1774 // before the split point and back into physical registers after the split
1775 // point. This prevents us needing to deal with Live-ins and many other
1776 // register allocation issues caused by us splitting the parent mbb. The
1777 // register allocator will clean up said virtual copies later on.
1778 MachineBasicBlock::iterator SplitPoint =
1780
1781 // Splice the terminator of ParentMBB into SuccessMBB.
1782 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1783 SplitPoint,
1784 ParentMBB->end());
1785
1786 // Add compare/jump on neq/jump to the parent BB.
1787 FuncInfo->MBB = ParentMBB;
1788 FuncInfo->InsertPt = ParentMBB->end();
1789 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1790 CurDAG->setRoot(SDB->getRoot());
1791 SDB->clear();
1792 CodeGenAndEmitDAG();
1793
1794 // CodeGen Failure MBB if we have not codegened it yet.
1795 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1796 if (FailureMBB->empty()) {
1797 FuncInfo->MBB = FailureMBB;
1798 FuncInfo->InsertPt = FailureMBB->end();
1799 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1800 CurDAG->setRoot(SDB->getRoot());
1801 SDB->clear();
1802 CodeGenAndEmitDAG();
1803 }
1804
1805 // Clear the Per-BB State.
1806 SDB->SPDescriptor.resetPerBBState();
1807 }
1808
1809 // Lower each BitTestBlock.
1810 for (auto &BTB : SDB->SL->BitTestCases) {
1811 // Lower header first, if it wasn't already lowered
1812 if (!BTB.Emitted) {
1813 // Set the current basic block to the mbb we wish to insert the code into
1814 FuncInfo->MBB = BTB.Parent;
1815 FuncInfo->InsertPt = FuncInfo->MBB->end();
1816 // Emit the code
1817 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1818 CurDAG->setRoot(SDB->getRoot());
1819 SDB->clear();
1820 CodeGenAndEmitDAG();
1821 }
1822
1823 BranchProbability UnhandledProb = BTB.Prob;
1824 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1825 UnhandledProb -= BTB.Cases[j].ExtraProb;
1826 // Set the current basic block to the mbb we wish to insert the code into
1827 FuncInfo->MBB = BTB.Cases[j].ThisBB;
1828 FuncInfo->InsertPt = FuncInfo->MBB->end();
1829 // Emit the code
1830
1831 // If all cases cover a contiguous range, it is not necessary to jump to
1832 // the default block after the last bit test fails. This is because the
1833 // range check during bit test header creation has guaranteed that every
1834 // case here doesn't go outside the range. In this case, there is no need
1835 // to perform the last bit test, as it will always be true. Instead, make
1836 // the second-to-last bit-test fall through to the target of the last bit
1837 // test, and delete the last bit test.
1838
1839 MachineBasicBlock *NextMBB;
1840 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
1841 // Second-to-last bit-test with contiguous range or omitted range
1842 // check: fall through to the target of the final bit test.
1843 NextMBB = BTB.Cases[j + 1].TargetBB;
1844 } else if (j + 1 == ej) {
1845 // For the last bit test, fall through to Default.
1846 NextMBB = BTB.Default;
1847 } else {
1848 // Otherwise, fall through to the next bit test.
1849 NextMBB = BTB.Cases[j + 1].ThisBB;
1850 }
1851
1852 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1853 FuncInfo->MBB);
1854
1855 CurDAG->setRoot(SDB->getRoot());
1856 SDB->clear();
1857 CodeGenAndEmitDAG();
1858
1859 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
1860 // Since we're not going to use the final bit test, remove it.
1861 BTB.Cases.pop_back();
1862 break;
1863 }
1864 }
1865
1866 // Update PHI Nodes
1867 for (const std::pair<MachineInstr *, unsigned> &P :
1868 FuncInfo->PHINodesToUpdate) {
1869 MachineInstrBuilder PHI(*MF, P.first);
1870 MachineBasicBlock *PHIBB = PHI->getParent();
1871 assert(PHI->isPHI() &&
1872 "This is not a machine PHI node that we are updating!");
1873 // This is "default" BB. We have two jumps to it. From "header" BB and
1874 // from last "case" BB, unless the latter was skipped.
1875 if (PHIBB == BTB.Default) {
1876 PHI.addReg(P.second).addMBB(BTB.Parent);
1877 if (!BTB.ContiguousRange) {
1878 PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
1879 }
1880 }
1881 // One of "cases" BB.
1882 for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
1883 MachineBasicBlock* cBB = BT.ThisBB;
1884 if (cBB->isSuccessor(PHIBB))
1885 PHI.addReg(P.second).addMBB(cBB);
1886 }
1887 }
1888 }
1889 SDB->SL->BitTestCases.clear();
1890
1891 // If the JumpTable record is filled in, then we need to emit a jump table.
1892 // Updating the PHI nodes is tricky in this case, since we need to determine
1893 // whether the PHI is a successor of the range check MBB or the jump table MBB
1894 for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
1895 // Lower header first, if it wasn't already lowered
1896 if (!SDB->SL->JTCases[i].first.Emitted) {
1897 // Set the current basic block to the mbb we wish to insert the code into
1898 FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
1899 FuncInfo->InsertPt = FuncInfo->MBB->end();
1900 // Emit the code
1901 SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
1902 SDB->SL->JTCases[i].first, FuncInfo->MBB);
1903 CurDAG->setRoot(SDB->getRoot());
1904 SDB->clear();
1905 CodeGenAndEmitDAG();
1906 }
1907
1908 // Set the current basic block to the mbb we wish to insert the code into
1909 FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
1910 FuncInfo->InsertPt = FuncInfo->MBB->end();
1911 // Emit the code
1912 SDB->visitJumpTable(SDB->SL->JTCases[i].second);
1913 CurDAG->setRoot(SDB->getRoot());
1914 SDB->clear();
1915 CodeGenAndEmitDAG();
1916
1917 // Update PHI Nodes
1918 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1919 pi != pe; ++pi) {
1920 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1921 MachineBasicBlock *PHIBB = PHI->getParent();
1922 assert(PHI->isPHI() &&
1923 "This is not a machine PHI node that we are updating!");
1924 // "default" BB. We can go there only from header BB.
1925 if (PHIBB == SDB->SL->JTCases[i].second.Default)
1926 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1927 .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
1928 // JT BB. Just iterate over successors here
1929 if (FuncInfo->MBB->isSuccessor(PHIBB))
1930 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1931 }
1932 }
1933 SDB->SL->JTCases.clear();
1934
1935 // If we generated any switch lowering information, build and codegen any
1936 // additional DAGs necessary.
1937 for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
1938 // Set the current basic block to the mbb we wish to insert the code into
1939 FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
1940 FuncInfo->InsertPt = FuncInfo->MBB->end();
1941
1942 // Determine the unique successors.
1944 Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
1945 if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
1946 Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
1947
1948 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1949 SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
1950 CurDAG->setRoot(SDB->getRoot());
1951 SDB->clear();
1952 CodeGenAndEmitDAG();
1953
1954 // Remember the last block, now that any splitting is done, for use in
1955 // populating PHI nodes in successors.
1956 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1957
1958 // Handle any PHI nodes in successors of this chunk, as if we were coming
1959 // from the original BB before switch expansion. Note that PHI nodes can
1960 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1961 // handle them the right number of times.
1962 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1963 FuncInfo->MBB = Succs[i];
1964 FuncInfo->InsertPt = FuncInfo->MBB->end();
1965 // FuncInfo->MBB may have been removed from the CFG if a branch was
1966 // constant folded.
1967 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1969 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1970 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1972 // This value for this PHI node is recorded in PHINodesToUpdate.
1973 for (unsigned pn = 0; ; ++pn) {
1974 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1975 "Didn't find PHI entry!");
1976 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1977 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1978 break;
1979 }
1980 }
1981 }
1982 }
1983 }
1984 }
1985 SDB->SL->SwitchCases.clear();
1986}
1987
1988/// Create the scheduler. If a specific scheduler was specified
1989/// via the SchedulerRegistry, use it, otherwise select the
1990/// one preferred by the target.
1991///
1992ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1993 return ISHeuristic(this, OptLevel);
1994}
1995
1996//===----------------------------------------------------------------------===//
1997// Helper functions used by the generated instruction selector.
1998//===----------------------------------------------------------------------===//
1999// Calls to these methods are generated by tblgen.
2000
2001/// CheckAndMask - The isel is trying to match something like (and X, 255). If
2002/// the dag combiner simplified the 255, we still want to match. RHS is the
2003/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2004/// specified in the .td file (e.g. 255).
2006 int64_t DesiredMaskS) const {
2007 const APInt &ActualMask = RHS->getAPIntValue();
2008 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2009
2010 // If the actual mask exactly matches, success!
2011 if (ActualMask == DesiredMask)
2012 return true;
2013
2014 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2015 if (!ActualMask.isSubsetOf(DesiredMask))
2016 return false;
2017
2018 // Otherwise, the DAG Combiner may have proven that the value coming in is
2019 // either already zero or is not demanded. Check for known zero input bits.
2020 APInt NeededMask = DesiredMask & ~ActualMask;
2021 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2022 return true;
2023
2024 // TODO: check to see if missing bits are just not demanded.
2025
2026 // Otherwise, this pattern doesn't match.
2027 return false;
2028}
2029
2030/// CheckOrMask - The isel is trying to match something like (or X, 255). If
2031/// the dag combiner simplified the 255, we still want to match. RHS is the
2032/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2033/// specified in the .td file (e.g. 255).
2035 int64_t DesiredMaskS) const {
2036 const APInt &ActualMask = RHS->getAPIntValue();
2037 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2038
2039 // If the actual mask exactly matches, success!
2040 if (ActualMask == DesiredMask)
2041 return true;
2042
2043 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2044 if (!ActualMask.isSubsetOf(DesiredMask))
2045 return false;
2046
2047 // Otherwise, the DAG Combiner may have proven that the value coming in is
2048 // either already zero or is not demanded. Check for known zero input bits.
2049 APInt NeededMask = DesiredMask & ~ActualMask;
2051
2052 // If all the missing bits in the or are already known to be set, match!
2053 if (NeededMask.isSubsetOf(Known.One))
2054 return true;
2055
2056 // TODO: check to see if missing bits are just not demanded.
2057
2058 // Otherwise, this pattern doesn't match.
2059 return false;
2060}
2061
2062/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2063/// by tblgen. Others should not call it.
2065 const SDLoc &DL) {
2066 std::vector<SDValue> InOps;
2067 std::swap(InOps, Ops);
2068
2069 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
2070 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
2071 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
2072 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2073
2074 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
2075 if (InOps[e-1].getValueType() == MVT::Glue)
2076 --e; // Don't process a glue operand if it is here.
2077
2078 while (i != e) {
2079 InlineAsm::Flag Flags(cast<ConstantSDNode>(InOps[i])->getZExtValue());
2080 if (!Flags.isMemKind() && !Flags.isFuncKind()) {
2081 // Just skip over this operand, copying the operands verbatim.
2082 Ops.insert(Ops.end(), InOps.begin() + i,
2083 InOps.begin() + i + Flags.getNumOperandRegisters() + 1);
2084 i += Flags.getNumOperandRegisters() + 1;
2085 } else {
2086 assert(Flags.getNumOperandRegisters() == 1 &&
2087 "Memory operand with multiple values?");
2088
2089 unsigned TiedToOperand;
2090 if (Flags.isUseOperandTiedToDef(TiedToOperand)) {
2091 // We need the constraint ID from the operand this is tied to.
2092 unsigned CurOp = InlineAsm::Op_FirstOperand;
2093 Flags =
2094 InlineAsm::Flag(cast<ConstantSDNode>(InOps[CurOp])->getZExtValue());
2095 for (; TiedToOperand; --TiedToOperand) {
2096 CurOp += Flags.getNumOperandRegisters() + 1;
2097 Flags = InlineAsm::Flag(
2098 cast<ConstantSDNode>(InOps[CurOp])->getZExtValue());
2099 }
2100 }
2101
2102 // Otherwise, this is a memory operand. Ask the target to select it.
2103 std::vector<SDValue> SelOps;
2104 const InlineAsm::ConstraintCode ConstraintID =
2105 Flags.getMemoryConstraintID();
2106 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
2107 report_fatal_error("Could not match memory address. Inline asm"
2108 " failure!");
2109
2110 // Add this to the output node.
2111 Flags = InlineAsm::Flag(Flags.isMemKind() ? InlineAsm::Kind::Mem
2113 SelOps.size());
2114 Flags.setMemConstraint(ConstraintID);
2115 Ops.push_back(CurDAG->getTargetConstant(Flags, DL, MVT::i32));
2116 llvm::append_range(Ops, SelOps);
2117 i += 2;
2118 }
2119 }
2120
2121 // Add the glue input back if present.
2122 if (e != InOps.size())
2123 Ops.push_back(InOps.back());
2124}
2125
2126/// findGlueUse - Return use of MVT::Glue value produced by the specified
2127/// SDNode.
2128///
2130 unsigned FlagResNo = N->getNumValues()-1;
2131 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2132 SDUse &Use = I.getUse();
2133 if (Use.getResNo() == FlagResNo)
2134 return Use.getUser();
2135 }
2136 return nullptr;
2137}
2138
2139/// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2140/// beyond "ImmedUse". We may ignore chains as they are checked separately.
2141static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2142 bool IgnoreChains) {
2145 // Only check if we have non-immediate uses of Def.
2146 if (ImmedUse->isOnlyUserOf(Def))
2147 return false;
2148
2149 // We don't care about paths to Def that go through ImmedUse so mark it
2150 // visited and mark non-def operands as used.
2151 Visited.insert(ImmedUse);
2152 for (const SDValue &Op : ImmedUse->op_values()) {
2153 SDNode *N = Op.getNode();
2154 // Ignore chain deps (they are validated by
2155 // HandleMergeInputChains) and immediate uses
2156 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2157 continue;
2158 if (!Visited.insert(N).second)
2159 continue;
2160 WorkList.push_back(N);
2161 }
2162
2163 // Initialize worklist to operands of Root.
2164 if (Root != ImmedUse) {
2165 for (const SDValue &Op : Root->op_values()) {
2166 SDNode *N = Op.getNode();
2167 // Ignore chains (they are validated by HandleMergeInputChains)
2168 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2169 continue;
2170 if (!Visited.insert(N).second)
2171 continue;
2172 WorkList.push_back(N);
2173 }
2174 }
2175
2176 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2177}
2178
2179/// IsProfitableToFold - Returns true if it's profitable to fold the specific
2180/// operand node N of U during instruction selection that starts at Root.
2182 SDNode *Root) const {
2184 return false;
2185 return N.hasOneUse();
2186}
2187
2188/// IsLegalToFold - Returns true if the specific operand node N of
2189/// U can be folded during instruction selection that starts at Root.
2191 CodeGenOptLevel OptLevel,
2192 bool IgnoreChains) {
2194 return false;
2195
2196 // If Root use can somehow reach N through a path that doesn't contain
2197 // U then folding N would create a cycle. e.g. In the following
2198 // diagram, Root can reach N through X. If N is folded into Root, then
2199 // X is both a predecessor and a successor of U.
2200 //
2201 // [N*] //
2202 // ^ ^ //
2203 // / \ //
2204 // [U*] [X]? //
2205 // ^ ^ //
2206 // \ / //
2207 // \ / //
2208 // [Root*] //
2209 //
2210 // * indicates nodes to be folded together.
2211 //
2212 // If Root produces glue, then it gets (even more) interesting. Since it
2213 // will be "glued" together with its glue use in the scheduler, we need to
2214 // check if it might reach N.
2215 //
2216 // [N*] //
2217 // ^ ^ //
2218 // / \ //
2219 // [U*] [X]? //
2220 // ^ ^ //
2221 // \ \ //
2222 // \ | //
2223 // [Root*] | //
2224 // ^ | //
2225 // f | //
2226 // | / //
2227 // [Y] / //
2228 // ^ / //
2229 // f / //
2230 // | / //
2231 // [GU] //
2232 //
2233 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2234 // (call it Fold), then X is a predecessor of GU and a successor of
2235 // Fold. But since Fold and GU are glued together, this will create
2236 // a cycle in the scheduling graph.
2237
2238 // If the node has glue, walk down the graph to the "lowest" node in the
2239 // glueged set.
2240 EVT VT = Root->getValueType(Root->getNumValues()-1);
2241 while (VT == MVT::Glue) {
2242 SDNode *GU = findGlueUse(Root);
2243 if (!GU)
2244 break;
2245 Root = GU;
2246 VT = Root->getValueType(Root->getNumValues()-1);
2247
2248 // If our query node has a glue result with a use, we've walked up it. If
2249 // the user (which has already been selected) has a chain or indirectly uses
2250 // the chain, HandleMergeInputChains will not consider it. Because of
2251 // this, we cannot ignore chains in this predicate.
2252 IgnoreChains = false;
2253 }
2254
2255 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2256}
2257
2258void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2259 SDLoc DL(N);
2260
2261 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2263
2264 const EVT VTs[] = {MVT::Other, MVT::Glue};
2265 SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2266 New->setNodeId(-1);
2267 ReplaceUses(N, New.getNode());
2269}
2270
2271void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2272 SDLoc dl(Op);
2273 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2274 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2275
2276 EVT VT = Op->getValueType(0);
2277 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2278 Register Reg =
2279 TLI->getRegisterByName(RegStr->getString().data(), Ty,
2282 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2283 New->setNodeId(-1);
2284 ReplaceUses(Op, New.getNode());
2286}
2287
2288void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2289 SDLoc dl(Op);
2290 MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2291 const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2292
2293 EVT VT = Op->getOperand(2).getValueType();
2294 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2295
2296 Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
2299 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2300 New->setNodeId(-1);
2301 ReplaceUses(Op, New.getNode());
2303}
2304
2305void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2306 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2307}
2308
2309void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2310 // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2311 // If FREEZE instruction is added later, the code below must be changed as
2312 // well.
2313 CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2314 N->getOperand(0));
2315}
2316
2317void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2318 CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2319 N->getOperand(0));
2320}
2321
2322void SelectionDAGISel::Select_MEMBARRIER(SDNode *N) {
2323 CurDAG->SelectNodeTo(N, TargetOpcode::MEMBARRIER, N->getValueType(0),
2324 N->getOperand(0));
2325}
2326
2327void SelectionDAGISel::pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops,
2328 SDValue OpVal, SDLoc DL) {
2329 SDNode *OpNode = OpVal.getNode();
2330
2331 // FrameIndex nodes should have been directly emitted to TargetFrameIndex
2332 // nodes at DAG-construction time.
2333 assert(OpNode->getOpcode() != ISD::FrameIndex);
2334
2335 if (OpNode->getOpcode() == ISD::Constant) {
2336 Ops.push_back(
2337 CurDAG->getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
2338 Ops.push_back(
2339 CurDAG->getTargetConstant(cast<ConstantSDNode>(OpNode)->getZExtValue(),
2340 DL, OpVal.getValueType()));
2341 } else {
2342 Ops.push_back(OpVal);
2343 }
2344}
2345
2346void SelectionDAGISel::Select_STACKMAP(SDNode *N) {
2348 auto *It = N->op_begin();
2349 SDLoc DL(N);
2350
2351 // Stash the chain and glue operands so we can move them to the end.
2352 SDValue Chain = *It++;
2353 SDValue InGlue = *It++;
2354
2355 // <id> operand.
2356 SDValue ID = *It++;
2357 assert(ID.getValueType() == MVT::i64);
2358 Ops.push_back(ID);
2359
2360 // <numShadowBytes> operand.
2361 SDValue Shad = *It++;
2362 assert(Shad.getValueType() == MVT::i32);
2363 Ops.push_back(Shad);
2364
2365 // Live variable operands.
2366 for (; It != N->op_end(); It++)
2367 pushStackMapLiveVariable(Ops, *It, DL);
2368
2369 Ops.push_back(Chain);
2370 Ops.push_back(InGlue);
2371
2372 SDVTList NodeTys = CurDAG->getVTList(MVT::Other, MVT::Glue);
2373 CurDAG->SelectNodeTo(N, TargetOpcode::STACKMAP, NodeTys, Ops);
2374}
2375
2376void SelectionDAGISel::Select_PATCHPOINT(SDNode *N) {
2378 auto *It = N->op_begin();
2379 SDLoc DL(N);
2380
2381 // Cache arguments that will be moved to the end in the target node.
2382 SDValue Chain = *It++;
2383 std::optional<SDValue> Glue;
2384 if (It->getValueType() == MVT::Glue)
2385 Glue = *It++;
2386 SDValue RegMask = *It++;
2387
2388 // <id> operand.
2389 SDValue ID = *It++;
2390 assert(ID.getValueType() == MVT::i64);
2391 Ops.push_back(ID);
2392
2393 // <numShadowBytes> operand.
2394 SDValue Shad = *It++;
2395 assert(Shad.getValueType() == MVT::i32);
2396 Ops.push_back(Shad);
2397
2398 // Add the callee.
2399 Ops.push_back(*It++);
2400
2401 // Add <numArgs>.
2402 SDValue NumArgs = *It++;
2403 assert(NumArgs.getValueType() == MVT::i32);
2404 Ops.push_back(NumArgs);
2405
2406 // Calling convention.
2407 Ops.push_back(*It++);
2408
2409 // Push the args for the call.
2410 for (uint64_t I = cast<ConstantSDNode>(NumArgs)->getZExtValue(); I != 0; I--)
2411 Ops.push_back(*It++);
2412
2413 // Now push the live variables.
2414 for (; It != N->op_end(); It++)
2415 pushStackMapLiveVariable(Ops, *It, DL);
2416
2417 // Finally, the regmask, chain and (if present) glue are moved to the end.
2418 Ops.push_back(RegMask);
2419 Ops.push_back(Chain);
2420 if (Glue.has_value())
2421 Ops.push_back(*Glue);
2422
2423 SDVTList NodeTys = N->getVTList();
2424 CurDAG->SelectNodeTo(N, TargetOpcode::PATCHPOINT, NodeTys, Ops);
2425}
2426
2427/// GetVBR - decode a vbr encoding whose top bit is set.
2429GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2430 assert(Val >= 128 && "Not a VBR");
2431 Val &= 127; // Remove first vbr bit.
2432
2433 unsigned Shift = 7;
2434 uint64_t NextBits;
2435 do {
2436 NextBits = MatcherTable[Idx++];
2437 Val |= (NextBits&127) << Shift;
2438 Shift += 7;
2439 } while (NextBits & 128);
2440
2441 return Val;
2442}
2443
2444void SelectionDAGISel::Select_JUMP_TABLE_DEBUG_INFO(SDNode *N) {
2445 SDLoc dl(N);
2446 CurDAG->SelectNodeTo(N, TargetOpcode::JUMP_TABLE_DEBUG_INFO, MVT::Glue,
2447 CurDAG->getTargetConstant(N->getConstantOperandVal(1),
2448 dl, MVT::i64, true));
2449}
2450
2451/// When a match is complete, this method updates uses of interior chain results
2452/// to use the new results.
2453void SelectionDAGISel::UpdateChains(
2454 SDNode *NodeToMatch, SDValue InputChain,
2455 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2456 SmallVector<SDNode*, 4> NowDeadNodes;
2457
2458 // Now that all the normal results are replaced, we replace the chain and
2459 // glue results if present.
2460 if (!ChainNodesMatched.empty()) {
2461 assert(InputChain.getNode() &&
2462 "Matched input chains but didn't produce a chain");
2463 // Loop over all of the nodes we matched that produced a chain result.
2464 // Replace all the chain results with the final chain we ended up with.
2465 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2466 SDNode *ChainNode = ChainNodesMatched[i];
2467 // If ChainNode is null, it's because we replaced it on a previous
2468 // iteration and we cleared it out of the map. Just skip it.
2469 if (!ChainNode)
2470 continue;
2471
2472 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2473 "Deleted node left in chain");
2474
2475 // Don't replace the results of the root node if we're doing a
2476 // MorphNodeTo.
2477 if (ChainNode == NodeToMatch && isMorphNodeTo)
2478 continue;
2479
2480 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2481 if (ChainVal.getValueType() == MVT::Glue)
2482 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2483 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2485 *CurDAG, [&](SDNode *N, SDNode *E) {
2486 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2487 static_cast<SDNode *>(nullptr));
2488 });
2489 if (ChainNode->getOpcode() != ISD::TokenFactor)
2490 ReplaceUses(ChainVal, InputChain);
2491
2492 // If the node became dead and we haven't already seen it, delete it.
2493 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2494 !llvm::is_contained(NowDeadNodes, ChainNode))
2495 NowDeadNodes.push_back(ChainNode);
2496 }
2497 }
2498
2499 if (!NowDeadNodes.empty())
2500 CurDAG->RemoveDeadNodes(NowDeadNodes);
2501
2502 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2503}
2504
2505/// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2506/// operation for when the pattern matched at least one node with a chains. The
2507/// input vector contains a list of all of the chained nodes that we match. We
2508/// must determine if this is a valid thing to cover (i.e. matching it won't
2509/// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2510/// be used as the input node chain for the generated nodes.
2511static SDValue
2513 SelectionDAG *CurDAG) {
2514
2517 SmallVector<SDValue, 3> InputChains;
2518 unsigned int Max = 8192;
2519
2520 // Quick exit on trivial merge.
2521 if (ChainNodesMatched.size() == 1)
2522 return ChainNodesMatched[0]->getOperand(0);
2523
2524 // Add chains that aren't already added (internal). Peek through
2525 // token factors.
2526 std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2527 if (V.getValueType() != MVT::Other)
2528 return;
2529 if (V->getOpcode() == ISD::EntryToken)
2530 return;
2531 if (!Visited.insert(V.getNode()).second)
2532 return;
2533 if (V->getOpcode() == ISD::TokenFactor) {
2534 for (const SDValue &Op : V->op_values())
2535 AddChains(Op);
2536 } else
2537 InputChains.push_back(V);
2538 };
2539
2540 for (auto *N : ChainNodesMatched) {
2541 Worklist.push_back(N);
2542 Visited.insert(N);
2543 }
2544
2545 while (!Worklist.empty())
2546 AddChains(Worklist.pop_back_val()->getOperand(0));
2547
2548 // Skip the search if there are no chain dependencies.
2549 if (InputChains.size() == 0)
2550 return CurDAG->getEntryNode();
2551
2552 // If one of these chains is a successor of input, we must have a
2553 // node that is both the predecessor and successor of the
2554 // to-be-merged nodes. Fail.
2555 Visited.clear();
2556 for (SDValue V : InputChains)
2557 Worklist.push_back(V.getNode());
2558
2559 for (auto *N : ChainNodesMatched)
2560 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2561 return SDValue();
2562
2563 // Return merged chain.
2564 if (InputChains.size() == 1)
2565 return InputChains[0];
2566 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2567 MVT::Other, InputChains);
2568}
2569
2570/// MorphNode - Handle morphing a node in place for the selector.
2571SDNode *SelectionDAGISel::
2572MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2573 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2574 // It is possible we're using MorphNodeTo to replace a node with no
2575 // normal results with one that has a normal result (or we could be
2576 // adding a chain) and the input could have glue and chains as well.
2577 // In this case we need to shift the operands down.
2578 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2579 // than the old isel though.
2580 int OldGlueResultNo = -1, OldChainResultNo = -1;
2581
2582 unsigned NTMNumResults = Node->getNumValues();
2583 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2584 OldGlueResultNo = NTMNumResults-1;
2585 if (NTMNumResults != 1 &&
2586 Node->getValueType(NTMNumResults-2) == MVT::Other)
2587 OldChainResultNo = NTMNumResults-2;
2588 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2589 OldChainResultNo = NTMNumResults-1;
2590
2591 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2592 // that this deletes operands of the old node that become dead.
2593 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2594
2595 // MorphNodeTo can operate in two ways: if an existing node with the
2596 // specified operands exists, it can just return it. Otherwise, it
2597 // updates the node in place to have the requested operands.
2598 if (Res == Node) {
2599 // If we updated the node in place, reset the node ID. To the isel,
2600 // this should be just like a newly allocated machine node.
2601 Res->setNodeId(-1);
2602 }
2603
2604 unsigned ResNumResults = Res->getNumValues();
2605 // Move the glue if needed.
2606 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2607 (unsigned)OldGlueResultNo != ResNumResults-1)
2608 ReplaceUses(SDValue(Node, OldGlueResultNo),
2609 SDValue(Res, ResNumResults - 1));
2610
2611 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2612 --ResNumResults;
2613
2614 // Move the chain reference if needed.
2615 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2616 (unsigned)OldChainResultNo != ResNumResults-1)
2617 ReplaceUses(SDValue(Node, OldChainResultNo),
2618 SDValue(Res, ResNumResults - 1));
2619
2620 // Otherwise, no replacement happened because the node already exists. Replace
2621 // Uses of the old node with the new one.
2622 if (Res != Node) {
2623 ReplaceNode(Node, Res);
2624 } else {
2626 }
2627
2628 return Res;
2629}
2630
2631/// CheckSame - Implements OP_CheckSame.
2633CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2634 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2635 // Accept if it is exactly the same as a previously recorded node.
2636 unsigned RecNo = MatcherTable[MatcherIndex++];
2637 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2638 return N == RecordedNodes[RecNo].first;
2639}
2640
2641/// CheckChildSame - Implements OP_CheckChildXSame.
2643 const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2644 const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2645 unsigned ChildNo) {
2646 if (ChildNo >= N.getNumOperands())
2647 return false; // Match fails if out of range child #.
2648 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2649 RecordedNodes);
2650}
2651
2652/// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2654CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2655 const SelectionDAGISel &SDISel, bool TwoBytePredNo) {
2656 unsigned PredNo = MatcherTable[MatcherIndex++];
2657 if (TwoBytePredNo)
2658 PredNo |= MatcherTable[MatcherIndex++] << 8;
2659 return SDISel.CheckPatternPredicate(PredNo);
2660}
2661
2662/// CheckNodePredicate - Implements OP_CheckNodePredicate.
2664CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2665 const SelectionDAGISel &SDISel, SDNode *N) {
2666 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2667}
2668
2670CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2671 SDNode *N) {
2672 uint16_t Opc = MatcherTable[MatcherIndex++];
2673 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2674 return N->getOpcode() == Opc;
2675}
2676
2678CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2679 const TargetLowering *TLI, const DataLayout &DL) {
2680 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2681 if (N.getValueType() == VT) return true;
2682
2683 // Handle the case when VT is iPTR.
2684 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2685}
2686
2688CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2689 SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2690 unsigned ChildNo) {
2691 if (ChildNo >= N.getNumOperands())
2692 return false; // Match fails if out of range child #.
2693 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2694 DL);
2695}
2696
2698CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2699 SDValue N) {
2700 return cast<CondCodeSDNode>(N)->get() ==
2701 (ISD::CondCode)MatcherTable[MatcherIndex++];
2702}
2703
2705CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2706 SDValue N) {
2707 if (2 >= N.getNumOperands())
2708 return false;
2709 return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
2710}
2711
2713CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2714 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2715 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2716 if (cast<VTSDNode>(N)->getVT() == VT)
2717 return true;
2718
2719 // Handle the case when VT is iPTR.
2720 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2721}
2722
2723// Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
2724// shifted left by 1.
2726 if ((V & 1) == 0)
2727 return V >> 1;
2728 if (V != 1)
2729 return -(V >> 1);
2730 // There is no such thing as -0 with integers. "-0" really means MININT.
2731 return 1ULL << 63;
2732}
2733
2735CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2736 SDValue N) {
2737 int64_t Val = MatcherTable[MatcherIndex++];
2738 if (Val & 128)
2739 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2740
2741 Val = decodeSignRotatedValue(Val);
2742
2743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2744 return C && C->getSExtValue() == Val;
2745}
2746
2748CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2749 SDValue N, unsigned ChildNo) {
2750 if (ChildNo >= N.getNumOperands())
2751 return false; // Match fails if out of range child #.
2752 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2753}
2754
2756CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2757 SDValue N, const SelectionDAGISel &SDISel) {
2758 int64_t Val = MatcherTable[MatcherIndex++];
2759 if (Val & 128)
2760 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2761
2762 if (N->getOpcode() != ISD::AND) return false;
2763
2764 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2765 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2766}
2767
2769CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2770 const SelectionDAGISel &SDISel) {
2771 int64_t Val = MatcherTable[MatcherIndex++];
2772 if (Val & 128)
2773 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2774
2775 if (N->getOpcode() != ISD::OR) return false;
2776
2777 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2778 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2779}
2780
2781/// IsPredicateKnownToFail - If we know how and can do so without pushing a
2782/// scope, evaluate the current node. If the current predicate is known to
2783/// fail, set Result=true and return anything. If the current predicate is
2784/// known to pass, set Result=false and return the MatcherIndex to continue
2785/// with. If the current predicate is unknown, set Result=false and return the
2786/// MatcherIndex to continue with.
2787static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2788 unsigned Index, SDValue N,
2789 bool &Result,
2790 const SelectionDAGISel &SDISel,
2791 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2792 switch (Table[Index++]) {
2793 default:
2794 Result = false;
2795 return Index-1; // Could not evaluate this predicate.
2797 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2798 return Index;
2803 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2805 return Index;
2808 Result = !::CheckPatternPredicate(
2809 Table, Index, SDISel,
2811 return Index;
2813 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2814 return Index;
2816 Result = !::CheckOpcode(Table, Index, N.getNode());
2817 return Index;
2819 Result = !::CheckType(Table, Index, N, SDISel.TLI,
2820 SDISel.CurDAG->getDataLayout());
2821 return Index;
2823 unsigned Res = Table[Index++];
2824 Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI,
2825 SDISel.CurDAG->getDataLayout());
2826 return Index;
2827 }
2836 Result = !::CheckChildType(
2837 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2839 return Index;
2841 Result = !::CheckCondCode(Table, Index, N);
2842 return Index;
2844 Result = !::CheckChild2CondCode(Table, Index, N);
2845 return Index;
2847 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2848 SDISel.CurDAG->getDataLayout());
2849 return Index;
2851 Result = !::CheckInteger(Table, Index, N);
2852 return Index;
2858 Result = !::CheckChildInteger(Table, Index, N,
2860 return Index;
2862 Result = !::CheckAndImm(Table, Index, N, SDISel);
2863 return Index;
2865 Result = !::CheckOrImm(Table, Index, N, SDISel);
2866 return Index;
2867 }
2868}
2869
2870namespace {
2871
2872struct MatchScope {
2873 /// FailIndex - If this match fails, this is the index to continue with.
2874 unsigned FailIndex;
2875
2876 /// NodeStack - The node stack when the scope was formed.
2877 SmallVector<SDValue, 4> NodeStack;
2878
2879 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2880 unsigned NumRecordedNodes;
2881
2882 /// NumMatchedMemRefs - The number of matched memref entries.
2883 unsigned NumMatchedMemRefs;
2884
2885 /// InputChain/InputGlue - The current chain/glue
2886 SDValue InputChain, InputGlue;
2887
2888 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2889 bool HasChainNodesMatched;
2890};
2891
2892/// \A DAG update listener to keep the matching state
2893/// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2894/// change the DAG while matching. X86 addressing mode matcher is an example
2895/// for this.
2896class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2897{
2898 SDNode **NodeToMatch;
2900 SmallVectorImpl<MatchScope> &MatchScopes;
2901
2902public:
2903 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2904 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2906 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2907 RecordedNodes(RN), MatchScopes(MS) {}
2908
2909 void NodeDeleted(SDNode *N, SDNode *E) override {
2910 // Some early-returns here to avoid the search if we deleted the node or
2911 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2912 // do, so it's unnecessary to update matching state at that point).
2913 // Neither of these can occur currently because we only install this
2914 // update listener during matching a complex patterns.
2915 if (!E || E->isMachineOpcode())
2916 return;
2917 // Check if NodeToMatch was updated.
2918 if (N == *NodeToMatch)
2919 *NodeToMatch = E;
2920 // Performing linear search here does not matter because we almost never
2921 // run this code. You'd have to have a CSE during complex pattern
2922 // matching.
2923 for (auto &I : RecordedNodes)
2924 if (I.first.getNode() == N)
2925 I.first.setNode(E);
2926
2927 for (auto &I : MatchScopes)
2928 for (auto &J : I.NodeStack)
2929 if (J.getNode() == N)
2930 J.setNode(E);
2931 }
2932};
2933
2934} // end anonymous namespace
2935
2937 const unsigned char *MatcherTable,
2938 unsigned TableSize) {
2939 // FIXME: Should these even be selected? Handle these cases in the caller?
2940 switch (NodeToMatch->getOpcode()) {
2941 default:
2942 break;
2943 case ISD::EntryToken: // These nodes remain the same.
2944 case ISD::BasicBlock:
2945 case ISD::Register:
2946 case ISD::RegisterMask:
2947 case ISD::HANDLENODE:
2948 case ISD::MDNODE_SDNODE:
2954 case ISD::MCSymbol:
2959 case ISD::TokenFactor:
2960 case ISD::CopyFromReg:
2961 case ISD::CopyToReg:
2962 case ISD::EH_LABEL:
2965 case ISD::LIFETIME_END:
2966 case ISD::PSEUDO_PROBE:
2967 NodeToMatch->setNodeId(-1); // Mark selected.
2968 return;
2969 case ISD::AssertSext:
2970 case ISD::AssertZext:
2971 case ISD::AssertAlign:
2972 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
2973 CurDAG->RemoveDeadNode(NodeToMatch);
2974 return;
2975 case ISD::INLINEASM:
2976 case ISD::INLINEASM_BR:
2977 Select_INLINEASM(NodeToMatch);
2978 return;
2979 case ISD::READ_REGISTER:
2980 Select_READ_REGISTER(NodeToMatch);
2981 return;
2983 Select_WRITE_REGISTER(NodeToMatch);
2984 return;
2985 case ISD::UNDEF:
2986 Select_UNDEF(NodeToMatch);
2987 return;
2988 case ISD::FREEZE:
2989 Select_FREEZE(NodeToMatch);
2990 return;
2991 case ISD::ARITH_FENCE:
2992 Select_ARITH_FENCE(NodeToMatch);
2993 return;
2994 case ISD::MEMBARRIER:
2995 Select_MEMBARRIER(NodeToMatch);
2996 return;
2997 case ISD::STACKMAP:
2998 Select_STACKMAP(NodeToMatch);
2999 return;
3000 case ISD::PATCHPOINT:
3001 Select_PATCHPOINT(NodeToMatch);
3002 return;
3004 Select_JUMP_TABLE_DEBUG_INFO(NodeToMatch);
3005 return;
3006 }
3007
3008 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
3009
3010 // Set up the node stack with NodeToMatch as the only node on the stack.
3011 SmallVector<SDValue, 8> NodeStack;
3012 SDValue N = SDValue(NodeToMatch, 0);
3013 NodeStack.push_back(N);
3014
3015 // MatchScopes - Scopes used when matching, if a match failure happens, this
3016 // indicates where to continue checking.
3017 SmallVector<MatchScope, 8> MatchScopes;
3018
3019 // RecordedNodes - This is the set of nodes that have been recorded by the
3020 // state machine. The second value is the parent of the node, or null if the
3021 // root is recorded.
3023
3024 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
3025 // pattern.
3027
3028 // These are the current input chain and glue for use when generating nodes.
3029 // Various Emit operations change these. For example, emitting a copytoreg
3030 // uses and updates these.
3031 SDValue InputChain, InputGlue;
3032
3033 // ChainNodesMatched - If a pattern matches nodes that have input/output
3034 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
3035 // which ones they are. The result is captured into this list so that we can
3036 // update the chain results when the pattern is complete.
3037 SmallVector<SDNode*, 3> ChainNodesMatched;
3038
3039 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
3040
3041 // Determine where to start the interpreter. Normally we start at opcode #0,
3042 // but if the state machine starts with an OPC_SwitchOpcode, then we
3043 // accelerate the first lookup (which is guaranteed to be hot) with the
3044 // OpcodeOffset table.
3045 unsigned MatcherIndex = 0;
3046
3047 if (!OpcodeOffset.empty()) {
3048 // Already computed the OpcodeOffset table, just index into it.
3049 if (N.getOpcode() < OpcodeOffset.size())
3050 MatcherIndex = OpcodeOffset[N.getOpcode()];
3051 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
3052
3053 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
3054 // Otherwise, the table isn't computed, but the state machine does start
3055 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
3056 // is the first time we're selecting an instruction.
3057 unsigned Idx = 1;
3058 while (true) {
3059 // Get the size of this case.
3060 unsigned CaseSize = MatcherTable[Idx++];
3061 if (CaseSize & 128)
3062 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
3063 if (CaseSize == 0) break;
3064
3065 // Get the opcode, add the index to the table.
3066 uint16_t Opc = MatcherTable[Idx++];
3067 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
3068 if (Opc >= OpcodeOffset.size())
3069 OpcodeOffset.resize((Opc+1)*2);
3070 OpcodeOffset[Opc] = Idx;
3071 Idx += CaseSize;
3072 }
3073
3074 // Okay, do the lookup for the first opcode.
3075 if (N.getOpcode() < OpcodeOffset.size())
3076 MatcherIndex = OpcodeOffset[N.getOpcode()];
3077 }
3078
3079 while (true) {
3080 assert(MatcherIndex < TableSize && "Invalid index");
3081#ifndef NDEBUG
3082 unsigned CurrentOpcodeIndex = MatcherIndex;
3083#endif
3084 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
3085 switch (Opcode) {
3086 case OPC_Scope: {
3087 // Okay, the semantics of this operation are that we should push a scope
3088 // then evaluate the first child. However, pushing a scope only to have
3089 // the first check fail (which then pops it) is inefficient. If we can
3090 // determine immediately that the first check (or first several) will
3091 // immediately fail, don't even bother pushing a scope for them.
3092 unsigned FailIndex;
3093
3094 while (true) {
3095 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3096 if (NumToSkip & 128)
3097 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3098 // Found the end of the scope with no match.
3099 if (NumToSkip == 0) {
3100 FailIndex = 0;
3101 break;
3102 }
3103
3104 FailIndex = MatcherIndex+NumToSkip;
3105
3106 unsigned MatcherIndexOfPredicate = MatcherIndex;
3107 (void)MatcherIndexOfPredicate; // silence warning.
3108
3109 // If we can't evaluate this predicate without pushing a scope (e.g. if
3110 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3111 // push the scope and evaluate the full predicate chain.
3112 bool Result;
3113 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
3114 Result, *this, RecordedNodes);
3115 if (!Result)
3116 break;
3117
3118 LLVM_DEBUG(
3119 dbgs() << " Skipped scope entry (due to false predicate) at "
3120 << "index " << MatcherIndexOfPredicate << ", continuing at "
3121 << FailIndex << "\n");
3122 ++NumDAGIselRetries;
3123
3124 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3125 // move to the next case.
3126 MatcherIndex = FailIndex;
3127 }
3128
3129 // If the whole scope failed to match, bail.
3130 if (FailIndex == 0) break;
3131
3132 // Push a MatchScope which indicates where to go if the first child fails
3133 // to match.
3134 MatchScope NewEntry;
3135 NewEntry.FailIndex = FailIndex;
3136 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3137 NewEntry.NumRecordedNodes = RecordedNodes.size();
3138 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3139 NewEntry.InputChain = InputChain;
3140 NewEntry.InputGlue = InputGlue;
3141 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3142 MatchScopes.push_back(NewEntry);
3143 continue;
3144 }
3145 case OPC_RecordNode: {
3146 // Remember this node, it may end up being an operand in the pattern.
3147 SDNode *Parent = nullptr;
3148 if (NodeStack.size() > 1)
3149 Parent = NodeStack[NodeStack.size()-2].getNode();
3150 RecordedNodes.push_back(std::make_pair(N, Parent));
3151 continue;
3152 }
3153
3158 unsigned ChildNo = Opcode-OPC_RecordChild0;
3159 if (ChildNo >= N.getNumOperands())
3160 break; // Match fails if out of range child #.
3161
3162 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
3163 N.getNode()));
3164 continue;
3165 }
3166 case OPC_RecordMemRef:
3167 if (auto *MN = dyn_cast<MemSDNode>(N))
3168 MatchedMemRefs.push_back(MN->getMemOperand());
3169 else {
3170 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3171 dbgs() << '\n');
3172 }
3173
3174 continue;
3175
3177 // If the current node has an input glue, capture it in InputGlue.
3178 if (N->getNumOperands() != 0 &&
3179 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3180 InputGlue = N->getOperand(N->getNumOperands()-1);
3181 continue;
3182
3183 case OPC_MoveChild: {
3184 unsigned ChildNo = MatcherTable[MatcherIndex++];
3185 if (ChildNo >= N.getNumOperands())
3186 break; // Match fails if out of range child #.
3187 N = N.getOperand(ChildNo);
3188 NodeStack.push_back(N);
3189 continue;
3190 }
3191
3192 case OPC_MoveChild0: case OPC_MoveChild1:
3193 case OPC_MoveChild2: case OPC_MoveChild3:
3194 case OPC_MoveChild4: case OPC_MoveChild5:
3195 case OPC_MoveChild6: case OPC_MoveChild7: {
3196 unsigned ChildNo = Opcode-OPC_MoveChild0;
3197 if (ChildNo >= N.getNumOperands())
3198 break; // Match fails if out of range child #.
3199 N = N.getOperand(ChildNo);
3200 NodeStack.push_back(N);
3201 continue;
3202 }
3203
3204 case OPC_MoveParent:
3205 // Pop the current node off the NodeStack.
3206 NodeStack.pop_back();
3207 assert(!NodeStack.empty() && "Node stack imbalance!");
3208 N = NodeStack.back();
3209 continue;
3210
3211 case OPC_CheckSame:
3212 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3213 continue;
3214
3217 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3218 Opcode-OPC_CheckChild0Same))
3219 break;
3220 continue;
3221
3224 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this,
3225 Opcode == OPC_CheckPatternPredicate2))
3226 break;
3227 continue;
3228 case OPC_CheckPredicate:
3229 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3230 N.getNode()))
3231 break;
3232 continue;
3234 unsigned OpNum = MatcherTable[MatcherIndex++];
3236
3237 for (unsigned i = 0; i < OpNum; ++i)
3238 Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3239
3240 unsigned PredNo = MatcherTable[MatcherIndex++];
3241 if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
3242 break;
3243 continue;
3244 }
3245 case OPC_CheckComplexPat: {
3246 unsigned CPNum = MatcherTable[MatcherIndex++];
3247 unsigned RecNo = MatcherTable[MatcherIndex++];
3248 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3249
3250 // If target can modify DAG during matching, keep the matching state
3251 // consistent.
3252 std::unique_ptr<MatchStateUpdater> MSU;
3254 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3255 MatchScopes));
3256
3257 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3258 RecordedNodes[RecNo].first, CPNum,
3259 RecordedNodes))
3260 break;
3261 continue;
3262 }
3263 case OPC_CheckOpcode:
3264 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3265 continue;
3266
3267 case OPC_CheckType:
3268 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3270 break;
3271 continue;
3272
3273 case OPC_CheckTypeRes: {
3274 unsigned Res = MatcherTable[MatcherIndex++];
3275 if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI,
3277 break;
3278 continue;
3279 }
3280
3281 case OPC_SwitchOpcode: {
3282 unsigned CurNodeOpcode = N.getOpcode();
3283 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3284 unsigned CaseSize;
3285 while (true) {
3286 // Get the size of this case.
3287 CaseSize = MatcherTable[MatcherIndex++];
3288 if (CaseSize & 128)
3289 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3290 if (CaseSize == 0) break;
3291
3292 uint16_t Opc = MatcherTable[MatcherIndex++];
3293 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3294
3295 // If the opcode matches, then we will execute this case.
3296 if (CurNodeOpcode == Opc)
3297 break;
3298
3299 // Otherwise, skip over this case.
3300 MatcherIndex += CaseSize;
3301 }
3302
3303 // If no cases matched, bail out.
3304 if (CaseSize == 0) break;
3305
3306 // Otherwise, execute the case we found.
3307 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3308 << MatcherIndex << "\n");
3309 continue;
3310 }
3311
3312 case OPC_SwitchType: {
3313 MVT CurNodeVT = N.getSimpleValueType();
3314 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3315 unsigned CaseSize;
3316 while (true) {
3317 // Get the size of this case.
3318 CaseSize = MatcherTable[MatcherIndex++];
3319 if (CaseSize & 128)
3320 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3321 if (CaseSize == 0) break;
3322
3323 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3324 if (CaseVT == MVT::iPTR)
3325 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3326
3327 // If the VT matches, then we will execute this case.
3328 if (CurNodeVT == CaseVT)
3329 break;
3330
3331 // Otherwise, skip over this case.
3332 MatcherIndex += CaseSize;
3333 }
3334
3335 // If no cases matched, bail out.
3336 if (CaseSize == 0) break;
3337
3338 // Otherwise, execute the case we found.
3339 LLVM_DEBUG(dbgs() << " TypeSwitch[" << CurNodeVT
3340 << "] from " << SwitchStart << " to " << MatcherIndex
3341 << '\n');
3342 continue;
3343 }
3348 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3350 Opcode - OPC_CheckChild0Type))
3351 break;
3352 continue;
3353 case OPC_CheckCondCode:
3354 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3355 continue;
3357 if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3358 continue;
3359 case OPC_CheckValueType:
3360 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3362 break;
3363 continue;
3364 case OPC_CheckInteger:
3365 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3366 continue;
3370 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3371 Opcode-OPC_CheckChild0Integer)) break;
3372 continue;
3373 case OPC_CheckAndImm:
3374 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3375 continue;
3376 case OPC_CheckOrImm:
3377 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3378 continue;
3380 if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3381 break;
3382 continue;
3384 if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3385 break;
3386 continue;
3387
3389 assert(NodeStack.size() != 1 && "No parent node");
3390 // Verify that all intermediate nodes between the root and this one have
3391 // a single use (ignoring chains, which are handled in UpdateChains).
3392 bool HasMultipleUses = false;
3393 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3394 unsigned NNonChainUses = 0;
3395 SDNode *NS = NodeStack[i].getNode();
3396 for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3397 if (UI.getUse().getValueType() != MVT::Other)
3398 if (++NNonChainUses > 1) {
3399 HasMultipleUses = true;
3400 break;
3401 }
3402 if (HasMultipleUses) break;
3403 }
3404 if (HasMultipleUses) break;
3405
3406 // Check to see that the target thinks this is profitable to fold and that
3407 // we can fold it without inducing cycles in the graph.
3408 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3409 NodeToMatch) ||
3410 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3411 NodeToMatch, OptLevel,
3412 true/*We validate our own chains*/))
3413 break;
3414
3415 continue;
3416 }
3417 case OPC_EmitInteger:
3418 case OPC_EmitStringInteger: {
3420 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3421 int64_t Val = MatcherTable[MatcherIndex++];
3422 if (Val & 128)
3423 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3424 if (Opcode == OPC_EmitInteger)
3425 Val = decodeSignRotatedValue(Val);
3426 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3427 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3428 VT), nullptr));
3429 continue;
3430 }
3431 case OPC_EmitRegister: {
3433 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3434 unsigned RegNo = MatcherTable[MatcherIndex++];
3435 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3436 CurDAG->getRegister(RegNo, VT), nullptr));
3437 continue;
3438 }
3439 case OPC_EmitRegister2: {
3440 // For targets w/ more than 256 register names, the register enum
3441 // values are stored in two bytes in the matcher table (just like
3442 // opcodes).
3444 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3445 unsigned RegNo = MatcherTable[MatcherIndex++];
3446 RegNo |= MatcherTable[MatcherIndex++] << 8;
3447 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3448 CurDAG->getRegister(RegNo, VT), nullptr));
3449 continue;
3450 }
3451
3453 // Convert from IMM/FPIMM to target version.
3454 unsigned RecNo = MatcherTable[MatcherIndex++];
3455 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3456 SDValue Imm = RecordedNodes[RecNo].first;
3457
3458 if (Imm->getOpcode() == ISD::Constant) {
3459 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3460 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3461 Imm.getValueType());
3462 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3463 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3464 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3465 Imm.getValueType());
3466 }
3467
3468 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3469 continue;
3470 }
3471
3472 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3473 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3474 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3475 // These are space-optimized forms of OPC_EmitMergeInputChains.
3476 assert(!InputChain.getNode() &&
3477 "EmitMergeInputChains should be the first chain producing node");
3478 assert(ChainNodesMatched.empty() &&
3479 "Should only have one EmitMergeInputChains per match");
3480
3481 // Read all of the chained nodes.
3482 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3483 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3484 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3485
3486 // If the chained node is not the root, we can't fold it if it has
3487 // multiple uses.
3488 // FIXME: What if other value results of the node have uses not matched
3489 // by this pattern?
3490 if (ChainNodesMatched.back() != NodeToMatch &&
3491 !RecordedNodes[RecNo].first.hasOneUse()) {
3492 ChainNodesMatched.clear();
3493 break;
3494 }
3495
3496 // Merge the input chains if they are not intra-pattern references.
3497 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3498
3499 if (!InputChain.getNode())
3500 break; // Failed to merge.
3501 continue;
3502 }
3503
3505 assert(!InputChain.getNode() &&
3506 "EmitMergeInputChains should be the first chain producing node");
3507 // This node gets a list of nodes we matched in the input that have
3508 // chains. We want to token factor all of the input chains to these nodes
3509 // together. However, if any of the input chains is actually one of the
3510 // nodes matched in this pattern, then we have an intra-match reference.
3511 // Ignore these because the newly token factored chain should not refer to
3512 // the old nodes.
3513 unsigned NumChains = MatcherTable[MatcherIndex++];
3514 assert(NumChains != 0 && "Can't TF zero chains");
3515
3516 assert(ChainNodesMatched.empty() &&
3517 "Should only have one EmitMergeInputChains per match");
3518
3519 // Read all of the chained nodes.
3520 for (unsigned i = 0; i != NumChains; ++i) {
3521 unsigned RecNo = MatcherTable[MatcherIndex++];
3522 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3523 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3524
3525 // If the chained node is not the root, we can't fold it if it has
3526 // multiple uses.
3527 // FIXME: What if other value results of the node have uses not matched
3528 // by this pattern?
3529 if (ChainNodesMatched.back() != NodeToMatch &&
3530 !RecordedNodes[RecNo].first.hasOneUse()) {
3531 ChainNodesMatched.clear();
3532 break;
3533 }
3534 }
3535
3536 // If the inner loop broke out, the match fails.
3537 if (ChainNodesMatched.empty())
3538 break;
3539
3540 // Merge the input chains if they are not intra-pattern references.
3541 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3542
3543 if (!InputChain.getNode())
3544 break; // Failed to merge.
3545
3546 continue;
3547 }
3548
3549 case OPC_EmitCopyToReg:
3550 case OPC_EmitCopyToReg2: {
3551 unsigned RecNo = MatcherTable[MatcherIndex++];
3552 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3553 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3554 if (Opcode == OPC_EmitCopyToReg2)
3555 DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
3556
3557 if (!InputChain.getNode())
3558 InputChain = CurDAG->getEntryNode();
3559
3560 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3561 DestPhysReg, RecordedNodes[RecNo].first,
3562 InputGlue);
3563
3564 InputGlue = InputChain.getValue(1);
3565 continue;
3566 }
3567
3568 case OPC_EmitNodeXForm: {
3569 unsigned XFormNo = MatcherTable[MatcherIndex++];
3570 unsigned RecNo = MatcherTable[MatcherIndex++];
3571 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3572 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3573 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3574 continue;
3575 }
3576 case OPC_Coverage: {
3577 // This is emitted right before MorphNode/EmitNode.
3578 // So it should be safe to assume that this node has been selected
3579 unsigned index = MatcherTable[MatcherIndex++];
3580 index |= (MatcherTable[MatcherIndex++] << 8);
3581 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3582 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3583 continue;
3584 }
3585
3586 case OPC_EmitNode: case OPC_MorphNodeTo:
3587 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
3589 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3590 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3591 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3592 // Get the result VT list.
3593 unsigned NumVTs;
3594 // If this is one of the compressed forms, get the number of VTs based
3595 // on the Opcode. Otherwise read the next byte from the table.
3596 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3597 NumVTs = Opcode - OPC_MorphNodeTo0;
3598 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3599 NumVTs = Opcode - OPC_EmitNode0;
3600 else
3601 NumVTs = MatcherTable[MatcherIndex++];
3603 for (unsigned i = 0; i != NumVTs; ++i) {
3605 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3606 if (VT == MVT::iPTR)
3607 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3608 VTs.push_back(VT);
3609 }
3610
3611 if (EmitNodeInfo & OPFL_Chain)
3612 VTs.push_back(MVT::Other);
3613 if (EmitNodeInfo & OPFL_GlueOutput)
3614 VTs.push_back(MVT::Glue);
3615
3616 // This is hot code, so optimize the two most common cases of 1 and 2
3617 // results.
3618 SDVTList VTList;
3619 if (VTs.size() == 1)
3620 VTList = CurDAG->getVTList(VTs[0]);
3621 else if (VTs.size() == 2)
3622 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3623 else
3624 VTList = CurDAG->getVTList(VTs);
3625
3626 // Get the operand list.
3627 unsigned NumOps = MatcherTable[MatcherIndex++];
3629 for (unsigned i = 0; i != NumOps; ++i) {
3630 unsigned RecNo = MatcherTable[MatcherIndex++];
3631 if (RecNo & 128)
3632 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3633
3634 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3635 Ops.push_back(RecordedNodes[RecNo].first);
3636 }
3637
3638 // If there are variadic operands to add, handle them now.
3639 if (EmitNodeInfo & OPFL_VariadicInfo) {
3640 // Determine the start index to copy from.
3641 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3642 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3643 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3644 "Invalid variadic node");
3645 // Copy all of the variadic operands, not including a potential glue
3646 // input.
3647 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3648 i != e; ++i) {
3649 SDValue V = NodeToMatch->getOperand(i);
3650 if (V.getValueType() == MVT::Glue) break;
3651 Ops.push_back(V);
3652 }
3653 }
3654
3655 // If this has chain/glue inputs, add them.
3656 if (EmitNodeInfo & OPFL_Chain)
3657 Ops.push_back(InputChain);
3658 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3659 Ops.push_back(InputGlue);
3660
3661 // Check whether any matched node could raise an FP exception. Since all
3662 // such nodes must have a chain, it suffices to check ChainNodesMatched.
3663 // We need to perform this check before potentially modifying one of the
3664 // nodes via MorphNode.
3665 bool MayRaiseFPException =
3666 llvm::any_of(ChainNodesMatched, [this](SDNode *N) {
3667 return mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept();
3668 });
3669
3670 // Create the node.
3671 MachineSDNode *Res = nullptr;
3672 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3673 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3674 if (!IsMorphNodeTo) {
3675 // If this is a normal EmitNode command, just create the new node and
3676 // add the results to the RecordedNodes list.
3677 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3678 VTList, Ops);
3679
3680 // Add all the non-glue/non-chain results to the RecordedNodes list.
3681 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3682 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3683 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3684 nullptr));
3685 }
3686 } else {
3687 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3688 "NodeToMatch was removed partway through selection");
3690 SDNode *E) {
3692 auto &Chain = ChainNodesMatched;
3693 assert((!E || !is_contained(Chain, N)) &&
3694 "Chain node replaced during MorphNode");
3695 llvm::erase_value(Chain, N);
3696 });
3697 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
3698 Ops, EmitNodeInfo));
3699 }
3700
3701 // Set the NoFPExcept flag when no original matched node could
3702 // raise an FP exception, but the new node potentially might.
3703 if (!MayRaiseFPException && mayRaiseFPException(Res)) {
3704 SDNodeFlags Flags = Res->getFlags();
3705 Flags.setNoFPExcept(true);
3706 Res->setFlags(Flags);
3707 }
3708
3709 // If the node had chain/glue results, update our notion of the current
3710 // chain and glue.
3711 if (EmitNodeInfo & OPFL_GlueOutput) {
3712 InputGlue = SDValue(Res, VTs.size()-1);
3713 if (EmitNodeInfo & OPFL_Chain)
3714 InputChain = SDValue(Res, VTs.size()-2);
3715 } else if (EmitNodeInfo & OPFL_Chain)
3716 InputChain = SDValue(Res, VTs.size()-1);
3717
3718 // If the OPFL_MemRefs glue is set on this node, slap all of the
3719 // accumulated memrefs onto it.
3720 //
3721 // FIXME: This is vastly incorrect for patterns with multiple outputs
3722 // instructions that access memory and for ComplexPatterns that match
3723 // loads.
3724 if (EmitNodeInfo & OPFL_MemRefs) {
3725 // Only attach load or store memory operands if the generated
3726 // instruction may load or store.
3727 const MCInstrDesc &MCID = TII->get(TargetOpc);
3728 bool mayLoad = MCID.mayLoad();
3729 bool mayStore = MCID.mayStore();
3730
3731 // We expect to have relatively few of these so just filter them into a
3732 // temporary buffer so that we can easily add them to the instruction.
3734 for (MachineMemOperand *MMO : MatchedMemRefs) {
3735 if (MMO->isLoad()) {
3736 if (mayLoad)
3737 FilteredMemRefs.push_back(MMO);
3738 } else if (MMO->isStore()) {
3739 if (mayStore)
3740 FilteredMemRefs.push_back(MMO);
3741 } else {
3742 FilteredMemRefs.push_back(MMO);
3743 }
3744 }
3745
3746 CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
3747 }
3748
3749 LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
3750 << " Dropping mem operands\n";
3751 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created")
3752 << " node: ";
3753 Res->dump(CurDAG););
3754
3755 // If this was a MorphNodeTo then we're completely done!
3756 if (IsMorphNodeTo) {
3757 // Update chain uses.
3758 UpdateChains(Res, InputChain, ChainNodesMatched, true);
3759 return;
3760 }
3761 continue;
3762 }
3763
3764 case OPC_CompleteMatch: {
3765 // The match has been completed, and any new nodes (if any) have been
3766 // created. Patch up references to the matched dag to use the newly
3767 // created nodes.
3768 unsigned NumResults = MatcherTable[MatcherIndex++];
3769
3770 for (unsigned i = 0; i != NumResults; ++i) {
3771 unsigned ResSlot = MatcherTable[MatcherIndex++];
3772 if (ResSlot & 128)
3773 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3774
3775 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3776 SDValue Res = RecordedNodes[ResSlot].first;
3777
3778 assert(i < NodeToMatch->getNumValues() &&
3779 NodeToMatch->getValueType(i) != MVT::Other &&
3780 NodeToMatch->getValueType(i) != MVT::Glue &&
3781 "Invalid number of results to complete!");
3782 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3783 NodeToMatch->getValueType(i) == MVT::iPTR ||
3784 Res.getValueType() == MVT::iPTR ||
3785 NodeToMatch->getValueType(i).getSizeInBits() ==
3786 Res.getValueSizeInBits()) &&
3787 "invalid replacement");
3788 ReplaceUses(SDValue(NodeToMatch, i), Res);
3789 }
3790
3791 // Update chain uses.
3792 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3793
3794 // If the root node defines glue, we need to update it to the glue result.
3795 // TODO: This never happens in our tests and I think it can be removed /
3796 // replaced with an assert, but if we do it this the way the change is
3797 // NFC.
3798 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3799 MVT::Glue &&
3800 InputGlue.getNode())
3801 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
3802 InputGlue);
3803
3804 assert(NodeToMatch->use_empty() &&
3805 "Didn't replace all uses of the node?");
3806 CurDAG->RemoveDeadNode(NodeToMatch);
3807
3808 return;
3809 }
3810 }
3811
3812 // If the code reached this point, then the match failed. See if there is
3813 // another child to try in the current 'Scope', otherwise pop it until we
3814 // find a case to check.
3815 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
3816 << "\n");
3817 ++NumDAGIselRetries;
3818 while (true) {
3819 if (MatchScopes.empty()) {
3820 CannotYetSelect(NodeToMatch);
3821 return;
3822 }
3823
3824 // Restore the interpreter state back to the point where the scope was
3825 // formed.
3826 MatchScope &LastScope = MatchScopes.back();
3827 RecordedNodes.resize(LastScope.NumRecordedNodes);
3828 NodeStack.clear();
3829 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3830 N = NodeStack.back();
3831
3832 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3833 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3834 MatcherIndex = LastScope.FailIndex;
3835
3836 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3837
3838 InputChain = LastScope.InputChain;
3839 InputGlue = LastScope.InputGlue;
3840 if (!LastScope.HasChainNodesMatched)
3841 ChainNodesMatched.clear();
3842
3843 // Check to see what the offset is at the new MatcherIndex. If it is zero
3844 // we have reached the end of this scope, otherwise we have another child
3845 // in the current scope to try.
3846 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3847 if (NumToSkip & 128)
3848 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3849
3850 // If we have another child in this scope to match, update FailIndex and
3851 // try it.
3852 if (NumToSkip != 0) {
3853 LastScope.FailIndex = MatcherIndex+NumToSkip;
3854 break;
3855 }
3856
3857 // End of this scope, pop it and try the next child in the containing
3858 // scope.
3859 MatchScopes.pop_back();
3860 }
3861 }
3862}
3863
3864/// Return whether the node may raise an FP exception.
3866 // For machine opcodes, consult the MCID flag.
3867 if (N->isMachineOpcode()) {
3868 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
3869 return MCID.mayRaiseFPException();
3870 }
3871
3872 // For ISD opcodes, only StrictFP opcodes may raise an FP
3873 // exception.
3874 if (N->isTargetOpcode())
3875 return N->isTargetStrictFPOpcode();
3876 return N->isStrictFPOpcode();
3877}
3878
3880 assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
3881 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3882 if (!C)
3883 return false;
3884
3885 // Detect when "or" is used to add an offset to a stack object.
3886 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
3888 Align A = MFI.getObjectAlign(FN->getIndex());
3889 int32_t Off = C->getSExtValue();
3890 // If the alleged offset fits in the zero bits guaranteed by
3891 // the alignment, then this or is really an add.
3892 return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
3893 }
3894 return false;
3895}
3896
3897void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3898 std::string msg;
3899 raw_string_ostream Msg(msg);
3900 Msg << "Cannot select: ";
3901
3902 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3903 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3904 N->getOpcode() != ISD::INTRINSIC_VOID) {
3905 N->printrFull(Msg, CurDAG);
3906 Msg << "\nIn function: " << MF->getName();
3907 } else {
3908 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3909 unsigned iid =
3910 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3911 if (iid < Intrinsic::num_intrinsics)
3912 Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
3913 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3914 Msg << "target intrinsic %" << TII->getName(iid);
3915 else
3916 Msg << "unknown intrinsic #" << iid;
3917 }
3919}
unsigned const MachineRegisterInfo * MRI
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
amdgpu AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockVerifier::State From
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ATTRIBUTE_ALWAYS_INLINE
LLVM_ATTRIBUTE_ALWAYS_INLINE - On compilers where we have a directive to do so, mark a method "always...
Definition: Compiler.h:242
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
bool End
Definition: ELF_riscv.cpp:469
This file defines the FastISel class.
IRTranslator LLVM IR MI
Select target instructions out of generic instructions
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine Instruction Scheduler
unsigned const TargetRegisterInfo * TRI
This file contains the declarations for metadata subclasses.
#define P(N)
const char LLVMTargetMachineRef TM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static cl::opt< bool > ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed"))
static cl::opt< bool > ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post " "legalize types dag combine pass"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
static cl::opt< bool > ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected"))
static LLVM_ATTRIBUTE_ALWAYS_INLINE uint64_t GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx)
GetVBR - decode a vbr encoding whose top bit is set.
static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F, MachineModuleInfo &MMI)
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
static cl::opt< bool > ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass"))
static RegisterScheduler defaultListDAGScheduler("default", "Best scheduler for the target", createDefaultScheduler)
static unsigned IsPredicateKnownToFail(const unsigned char *Table, unsigned Index, SDValue N, bool &Result, const SelectionDAGISel &SDISel, SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
IsPredicateKnownToFail - If we know how and can do so without pushing a scope, evaluate the current n...
static cl::opt< int > EnableFastISelAbort("fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG."))
static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, const CatchPadInst *CPI)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, SDNode *N)
CheckNodePredicate - Implements OP_CheckNodePredicate.
static void processSingleLocVars(FunctionLoweringInfo &FuncInfo, FunctionVarLocs const *FnVarLocs)
Collect single location variable information generated with assignment tracking.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
static cl::opt< bool > UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * > > &RecordedNodes)
CheckSame - Implements OP_CheckSame.
static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, bool IgnoreChains)
findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path beyond "ImmedUse".
static cl::opt< bool > ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass"))
static bool processIfEntryValueDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Arg, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static cl::opt< bool > ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed"))
static void processDbgDeclares(FunctionLoweringInfo &FuncInfo)
Collect llvm.dbg.declare information.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL, unsigned ChildNo)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
static cl::opt< bool > ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize"))
static cl::opt< bool > ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types"))
static SDNode * findGlueUse(SDNode *N)
findGlueUse - Return use of MVT::Glue value produced by the specified SDNode.
static cl::opt< RegisterScheduler::FunctionPassCtor, false, RegisterPassParser< RegisterScheduler > > ISHeuristic("pre-RA-sched", cl::init(&createDefaultScheduler), cl::Hidden, cl::desc("Instruction schedulers available (before register" " allocation):"))
ISHeuristic command line option for instruction schedulers.
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, bool TwoBytePredNo)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
static cl::opt< bool > EnableFastISelFallbackReport("fast-isel-report-on-fallback", cl::Hidden, cl::desc("Emit a diagnostic when \"fast\" instruction selection " "falls back to SelectionDAG."))
static bool processDbgDeclare(FunctionLoweringInfo &FuncInfo, const Value *Address, DIExpression *Expr, DILocalVariable *Var, DebugLoc DbgLoc)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDNode *N)
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, unsigned ChildNo)
static cl::opt< std::string > FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options"))
static SDValue HandleMergeInputChains(SmallVectorImpl< SDNode * > &ChainNodesMatched, SelectionDAG *CurDAG)
HandleMergeInputChains - This implements the OPC_EmitMergeInputChains operation for when the pattern ...
static bool isFoldedOrDeadInstruction(const Instruction *I, const FunctionLoweringInfo &FuncInfo)
isFoldedOrDeadInstruction - Return true if the specified instruction is side-effect free and is eithe...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
DEMANGLE_DUMP_METHOD void dump() const
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition: APInt.h:76
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1229
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator end()
Definition: BasicBlock.h:337
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:393
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:88
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:216
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:533
const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
Definition: BasicBlock.cpp:207
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Legacy analysis pass which computes BranchProbabilityInfo.
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:260
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
This is an important base class in LLVM.
Definition: Constant.h:41
DWARF expression.
bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A debug info location.
Definition: DebugLoc.h:33
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Diagnostic information for ISel fallback path.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition: FastISel.h:66
void setLastLocalValue(MachineInstr *I)
Update the position of the last instruction emitted for materializing constants for use in the curren...
Definition: FastISel.h:237
bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst)
We're checking to see if we can fold LI into FoldInst.
Definition: FastISel.cpp:2219
void removeDeadCode(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
Remove all dead instructions between the I and E.
Definition: FastISel.cpp:410
void startNewBlock()
Set the current block to which generated machine instructions will be appended.
Definition: FastISel.cpp:123
bool selectInstruction(const Instruction *I)
Do "fast" instruction selection for the given LLVM IR instruction and append the generated machine in...
Definition: FastISel.cpp:1498
void finishBasicBlock()
Flush the local value map.
Definition: FastISel.cpp:136
void recomputeInsertPt()
Reset InsertPt to prepare for inserting instructions into the current block.
Definition: FastISel.cpp:401
bool lowerArguments()
Do "fast" instruction selection for function arguments and append the machine instructions to the cur...
Definition: FastISel.cpp:138
unsigned arg_size() const
arg_size - Return the number of funcletpad arguments.
Definition: InstrTypes.h:2348
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
Definition: InstrTypes.h:2364
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
int getArgumentFrameIndex(const Argument *A)
getArgumentFrameIndex - Get frame index for the byval argument.
bool isExportedInst(const Value *V) const
isExportedInst - Return true if the specified value is an instruction exported from its block.
SmallPtrSet< const DbgDeclareInst *, 8 > PreprocessedDbgDeclares
Collection of dbg.declare instructions handled after argument lowering and before ISel proper.
DenseMap< const Value *, Register > ValueMap
ValueMap - Since we emit code for the function a basic block at a time, we must remember which virtua...
MachineRegisterInfo * RegInfo
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:178
Data structure describing the variable locations in a function.
const VarLocInfo * single_locs_begin() const
DILocalVariable * getDILocalVariable(const VarLocInfo *Loc) const
Return the DILocalVariable for the location definition represented by ID.
const VarLocInfo * single_locs_end() const
One past the last single-location variable location definition.
const BasicBlock & getEntryBlock() const
Definition: Function.h:747
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:176
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1727
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition: Function.h:307
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:320
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
Definition: Function.cpp:1836
An analysis pass which caches information about the entire Module.
Definition: GCMetadata.h:152
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
This class is used to form a handle around another node that is persistent and is updated across invo...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:392
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Definition: MCContext.cpp:322
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
bool mayStore() const
Return true if this instruction could possibly modify memory.
Definition: MCInstrDesc.h:444
bool mayLoad() const
Return true if this instruction could possibly read memory.
Definition: MCInstrDesc.h:438
bool mayRaiseFPException() const
Return true if this instruction may raise a floating-point exception.
Definition: MCInstrDesc.h:447
bool isCall() const
Return true if the instruction is a call.
Definition: MCInstrDesc.h:288
bool isReturn() const
Return true if the instruction is a return.
Definition: MCInstrDesc.h:276
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:63
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition: MCInstrInfo.h:70
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
const MDNode * getMD() const
Metadata node.
Definition: Metadata.h:950
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1303
A single uniqued string.
Definition: Metadata.h:611
StringRef getString() const
Definition: Metadata.cpp:509
Machine Value Type.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
instr_iterator instr_end()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasCalls() const
Return true if the current function has any function calls.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool hasProperty(Property P) const
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setExposesReturnsTwice(bool B)
setCallsSetJmp - Set a flag that indicates if there's a call to a "returns twice" function.
void setHasInlineAsm(bool B)
Set a flag that indicates that the function contains inline assembly.
void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index)
Map the landing pad to its index. Used for Wasm exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void finalizeDebugInstrRefs()
Finalise any partially emitted debug instructions.
void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef< unsigned > Sites)
Map the landing pad's EH symbol to the call site indexes.
void setUseDebugInstrRef(bool UseInstrRef)
Set whether this function will use instruction referencing or not.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
MCSymbol * addLandingPad(MachineBasicBlock *LandingPad)
Add a new panding pad, and extract the exception handling information from the landingpad instruction...
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineModuleInfo & getMMI() const
bool shouldUseDebugInstrRef() const
Determine whether, in the current machine configuration, we should use instruction referencing or not...
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
const MachineBasicBlock & front() const
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:68
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:939
bool isCopy() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:326
bool isDebugValue() const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:553
A description of a memory reference used in the backend.
This class contains meta information specific to a module.
const MCContext & getContext() const
bool usesMSVCFloatingPoint() const
void setUsesMSVCFloatingPoint(bool b)
Register getReg() const
getReg - Returns the register number.
MachinePassRegistry - Track the registration of machine passes.
defusechain_iterator - This class provides iterator support for machine operands in the function that...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
void EmitLiveInCopies(MachineBasicBlock *EntryMBB, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII)
EmitLiveInCopies - Emit copies to initialize livein virtual registers into the given entry block.
use_instr_iterator use_instr_begin(Register RegNo) const
ArrayRef< std::pair< MCRegister, Register > > liveins() const
static use_instr_iterator use_instr_end()
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
An SDNode that represents everything that will be needed to construct a MachineInstr.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:322
This class is used by SelectionDAGISel to temporarily override the optimization level on a per-functi...
OptLevelChanger(SelectionDAGISel &ISel, CodeGenOptLevel NewOptLevel)
The optimization diagnostic interface.
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
RegisterPassParser class - Handle the addition of new machine passes.
ScheduleDAGSDNodes *(*)(SelectionDAGISel *, CodeGenOptLevel) FunctionPassCtor
static MachinePassRegistry< FunctionPassCtor > Registry
RegisterScheduler class - Track the registration of instruction schedulers.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static unsigned virtReg2Index(Register Reg)
Convert a virtual register number to a 0-based index.
Definition: Register.h:77
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:71
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
void setNodeId(int Id)
Set unique node id.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
static use_iterator use_end()
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
AssumptionCache * AC
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
MachineFunction * MF
virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
MachineRegisterInfo * RegInfo
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
@ OPC_RecordChild7
Definition: