1 //===- llvm/CodeGen/MachineFunction.h ---------------------------*- C++ -*-===// 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 // Collect native machine code for a function. This class contains a list of 10 // MachineBasicBlock instances that make up the current compiled function. 11 // 12 // This class also contains pointers to various classes which hold 13 // target-specific information about the generated code. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H 18 #define LLVM_CODEGEN_MACHINEFUNCTION_H 19 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/BitVector.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/GraphTraits.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/ilist.h" 26 #include "llvm/ADT/iterator.h" 27 #include "llvm/Analysis/EHPersonalities.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineMemOperand.h" 31 #include "llvm/Support/Allocator.h" 32 #include "llvm/Support/ArrayRecycler.h" 33 #include "llvm/Support/AtomicOrdering.h" 34 #include "llvm/Support/Compiler.h" 35 #include "llvm/Support/Recycler.h" 36 #include "llvm/Target/TargetOptions.h" 37 #include <cassert> 38 #include <cstdint> 39 #include <memory> 40 #include <utility> 41 #include <vector> 42 43 namespace llvm { 44 45 class BasicBlock; 46 class BlockAddress; 47 class DataLayout; 48 class DebugLoc; 49 struct DenormalMode; 50 class DIExpression; 51 class DILocalVariable; 52 class DILocation; 53 class Function; 54 class GISelChangeObserver; 55 class GlobalValue; 56 class LLVMTargetMachine; 57 class MachineConstantPool; 58 class MachineFrameInfo; 59 class MachineFunction; 60 class MachineJumpTableInfo; 61 class MachineModuleInfo; 62 class MachineRegisterInfo; 63 class MCContext; 64 class MCInstrDesc; 65 class MCSymbol; 66 class MCSection; 67 class Pass; 68 class PseudoSourceValueManager; 69 class raw_ostream; 70 class SlotIndexes; 71 class StringRef; 72 class TargetRegisterClass; 73 class TargetSubtargetInfo; 74 struct WasmEHFuncInfo; 75 struct WinEHFuncInfo; 76 77 template <> struct ilist_alloc_traits<MachineBasicBlock> { 78 void deleteNode(MachineBasicBlock *MBB); 79 }; 80 81 template <> struct ilist_callback_traits<MachineBasicBlock> { 82 void addNodeToList(MachineBasicBlock* N); 83 void removeNodeFromList(MachineBasicBlock* N); 84 85 template <class Iterator> 86 void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) { 87 assert(this == &OldList && "never transfer MBBs between functions"); 88 } 89 }; 90 91 /// MachineFunctionInfo - This class can be derived from and used by targets to 92 /// hold private target-specific information for each MachineFunction. Objects 93 /// of type are accessed/created with MF::getInfo and destroyed when the 94 /// MachineFunction is destroyed. 95 struct MachineFunctionInfo { 96 virtual ~MachineFunctionInfo(); 97 98 /// Factory function: default behavior is to call new using the 99 /// supplied allocator. 100 /// 101 /// This function can be overridden in a derive class. 102 template<typename Ty> 103 static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) { 104 return new (Allocator.Allocate<Ty>()) Ty(MF); 105 } 106 }; 107 108 /// Properties which a MachineFunction may have at a given point in time. 109 /// Each of these has checking code in the MachineVerifier, and passes can 110 /// require that a property be set. 111 class MachineFunctionProperties { 112 // Possible TODO: Allow targets to extend this (perhaps by allowing the 113 // constructor to specify the size of the bit vector) 114 // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be 115 // stated as the negative of "has vregs" 116 117 public: 118 // The properties are stated in "positive" form; i.e. a pass could require 119 // that the property hold, but not that it does not hold. 120 121 // Property descriptions: 122 // IsSSA: True when the machine function is in SSA form and virtual registers 123 // have a single def. 124 // NoPHIs: The machine function does not contain any PHI instruction. 125 // TracksLiveness: True when tracking register liveness accurately. 126 // While this property is set, register liveness information in basic block 127 // live-in lists and machine instruction operands (e.g. kill flags, implicit 128 // defs) is accurate. This means it can be used to change the code in ways 129 // that affect the values in registers, for example by the register 130 // scavenger. 131 // When this property is clear, liveness is no longer reliable. 132 // NoVRegs: The machine function does not use any virtual registers. 133 // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic 134 // instructions have been legalized; i.e., all instructions are now one of: 135 // - generic and always legal (e.g., COPY) 136 // - target-specific 137 // - legal pre-isel generic instructions. 138 // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic 139 // virtual registers have been assigned to a register bank. 140 // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel 141 // generic instructions have been eliminated; i.e., all instructions are now 142 // target-specific or non-pre-isel generic instructions (e.g., COPY). 143 // Since only pre-isel generic instructions can have generic virtual register 144 // operands, this also means that all generic virtual registers have been 145 // constrained to virtual registers (assigned to register classes) and that 146 // all sizes attached to them have been eliminated. 147 // TiedOpsRewritten: The twoaddressinstruction pass will set this flag, it 148 // means that tied-def have been rewritten to meet the RegConstraint. 149 enum class Property : unsigned { 150 IsSSA, 151 NoPHIs, 152 TracksLiveness, 153 NoVRegs, 154 FailedISel, 155 Legalized, 156 RegBankSelected, 157 Selected, 158 TiedOpsRewritten, 159 LastProperty = TiedOpsRewritten, 160 }; 161 162 bool hasProperty(Property P) const { 163 return Properties[static_cast<unsigned>(P)]; 164 } 165 166 MachineFunctionProperties &set(Property P) { 167 Properties.set(static_cast<unsigned>(P)); 168 return *this; 169 } 170 171 MachineFunctionProperties &reset(Property P) { 172 Properties.reset(static_cast<unsigned>(P)); 173 return *this; 174 } 175 176 /// Reset all the properties. 177 MachineFunctionProperties &reset() { 178 Properties.reset(); 179 return *this; 180 } 181 182 MachineFunctionProperties &set(const MachineFunctionProperties &MFP) { 183 Properties |= MFP.Properties; 184 return *this; 185 } 186 187 MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) { 188 Properties.reset(MFP.Properties); 189 return *this; 190 } 191 192 // Returns true if all properties set in V (i.e. required by a pass) are set 193 // in this. 194 bool verifyRequiredProperties(const MachineFunctionProperties &V) const { 195 return !V.Properties.test(Properties); 196 } 197 198 /// Print the MachineFunctionProperties in human-readable form. 199 void print(raw_ostream &OS) const; 200 201 private: 202 BitVector Properties = 203 BitVector(static_cast<unsigned>(Property::LastProperty)+1); 204 }; 205 206 struct SEHHandler { 207 /// Filter or finally function. Null indicates a catch-all. 208 const Function *FilterOrFinally; 209 210 /// Address of block to recover at. Null for a finally handler. 211 const BlockAddress *RecoverBA; 212 }; 213 214 /// This structure is used to retain landing pad info for the current function. 215 struct LandingPadInfo { 216 MachineBasicBlock *LandingPadBlock; // Landing pad block. 217 SmallVector<MCSymbol *, 1> BeginLabels; // Labels prior to invoke. 218 SmallVector<MCSymbol *, 1> EndLabels; // Labels after invoke. 219 SmallVector<SEHHandler, 1> SEHHandlers; // SEH handlers active at this lpad. 220 MCSymbol *LandingPadLabel = nullptr; // Label at beginning of landing pad. 221 std::vector<int> TypeIds; // List of type ids (filters negative). 222 223 explicit LandingPadInfo(MachineBasicBlock *MBB) 224 : LandingPadBlock(MBB) {} 225 }; 226 227 class MachineFunction { 228 Function &F; 229 const LLVMTargetMachine &Target; 230 const TargetSubtargetInfo *STI; 231 MCContext &Ctx; 232 MachineModuleInfo &MMI; 233 234 // RegInfo - Information about each register in use in the function. 235 MachineRegisterInfo *RegInfo; 236 237 // Used to keep track of target-specific per-machine function information for 238 // the target implementation. 239 MachineFunctionInfo *MFInfo; 240 241 // Keep track of objects allocated on the stack. 242 MachineFrameInfo *FrameInfo; 243 244 // Keep track of constants which are spilled to memory 245 MachineConstantPool *ConstantPool; 246 247 // Keep track of jump tables for switch instructions 248 MachineJumpTableInfo *JumpTableInfo; 249 250 // Keep track of the function section. 251 MCSection *Section = nullptr; 252 253 // Keeps track of Wasm exception handling related data. This will be null for 254 // functions that aren't using a wasm EH personality. 255 WasmEHFuncInfo *WasmEHInfo = nullptr; 256 257 // Keeps track of Windows exception handling related data. This will be null 258 // for functions that aren't using a funclet-based EH personality. 259 WinEHFuncInfo *WinEHInfo = nullptr; 260 261 // Function-level unique numbering for MachineBasicBlocks. When a 262 // MachineBasicBlock is inserted into a MachineFunction is it automatically 263 // numbered and this vector keeps track of the mapping from ID's to MBB's. 264 std::vector<MachineBasicBlock*> MBBNumbering; 265 266 // Unary encoding of basic block symbols is used to reduce size of ".strtab". 267 // Basic block number 'i' gets a prefix of length 'i'. The ith character also 268 // denotes the type of basic block number 'i'. Return blocks are marked with 269 // 'r', landing pads with 'l' and regular blocks with 'a'. 270 std::vector<char> BBSectionsSymbolPrefix; 271 272 // Pool-allocate MachineFunction-lifetime and IR objects. 273 BumpPtrAllocator Allocator; 274 275 // Allocation management for instructions in function. 276 Recycler<MachineInstr> InstructionRecycler; 277 278 // Allocation management for operand arrays on instructions. 279 ArrayRecycler<MachineOperand> OperandRecycler; 280 281 // Allocation management for basic blocks in function. 282 Recycler<MachineBasicBlock> BasicBlockRecycler; 283 284 // List of machine basic blocks in function 285 using BasicBlockListType = ilist<MachineBasicBlock>; 286 BasicBlockListType BasicBlocks; 287 288 /// FunctionNumber - This provides a unique ID for each function emitted in 289 /// this translation unit. 290 /// 291 unsigned FunctionNumber; 292 293 /// Alignment - The alignment of the function. 294 Align Alignment; 295 296 /// ExposesReturnsTwice - True if the function calls setjmp or related 297 /// functions with attribute "returns twice", but doesn't have 298 /// the attribute itself. 299 /// This is used to limit optimizations which cannot reason 300 /// about the control flow of such functions. 301 bool ExposesReturnsTwice = false; 302 303 /// True if the function includes any inline assembly. 304 bool HasInlineAsm = false; 305 306 /// True if any WinCFI instruction have been emitted in this function. 307 bool HasWinCFI = false; 308 309 /// Current high-level properties of the IR of the function (e.g. is in SSA 310 /// form or whether registers have been allocated) 311 MachineFunctionProperties Properties; 312 313 // Allocation management for pseudo source values. 314 std::unique_ptr<PseudoSourceValueManager> PSVManager; 315 316 /// List of moves done by a function's prolog. Used to construct frame maps 317 /// by debug and exception handling consumers. 318 std::vector<MCCFIInstruction> FrameInstructions; 319 320 /// List of basic blocks immediately following calls to _setjmp. Used to 321 /// construct a table of valid longjmp targets for Windows Control Flow Guard. 322 std::vector<MCSymbol *> LongjmpTargets; 323 324 /// \name Exception Handling 325 /// \{ 326 327 /// List of LandingPadInfo describing the landing pad information. 328 std::vector<LandingPadInfo> LandingPads; 329 330 /// Map a landing pad's EH symbol to the call site indexes. 331 DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap; 332 333 /// Map a landing pad to its index. 334 DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap; 335 336 /// Map of invoke call site index values to associated begin EH_LABEL. 337 DenseMap<MCSymbol*, unsigned> CallSiteMap; 338 339 /// CodeView label annotations. 340 std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations; 341 342 bool CallsEHReturn = false; 343 bool CallsUnwindInit = false; 344 bool HasEHScopes = false; 345 bool HasEHFunclets = false; 346 347 /// Section Type for basic blocks, only relevant with basic block sections. 348 BasicBlockSection BBSectionsType = BasicBlockSection::None; 349 350 /// List of C++ TypeInfo used. 351 std::vector<const GlobalValue *> TypeInfos; 352 353 /// List of typeids encoding filters used. 354 std::vector<unsigned> FilterIds; 355 356 /// List of the indices in FilterIds corresponding to filter terminators. 357 std::vector<unsigned> FilterEnds; 358 359 EHPersonality PersonalityTypeCache = EHPersonality::Unknown; 360 361 /// \} 362 363 /// Clear all the members of this MachineFunction, but the ones used 364 /// to initialize again the MachineFunction. 365 /// More specifically, this deallocates all the dynamically allocated 366 /// objects and get rid of all the XXXInfo data structure, but keep 367 /// unchanged the references to Fn, Target, MMI, and FunctionNumber. 368 void clear(); 369 /// Allocate and initialize the different members. 370 /// In particular, the XXXInfo data structure. 371 /// \pre Fn, Target, MMI, and FunctionNumber are properly set. 372 void init(); 373 374 public: 375 struct VariableDbgInfo { 376 const DILocalVariable *Var; 377 const DIExpression *Expr; 378 // The Slot can be negative for fixed stack objects. 379 int Slot; 380 const DILocation *Loc; 381 382 VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, 383 int Slot, const DILocation *Loc) 384 : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {} 385 }; 386 387 class Delegate { 388 virtual void anchor(); 389 390 public: 391 virtual ~Delegate() = default; 392 /// Callback after an insertion. This should not modify the MI directly. 393 virtual void MF_HandleInsertion(MachineInstr &MI) = 0; 394 /// Callback before a removal. This should not modify the MI directly. 395 virtual void MF_HandleRemoval(MachineInstr &MI) = 0; 396 }; 397 398 /// Structure used to represent pair of argument number after call lowering 399 /// and register used to transfer that argument. 400 /// For now we support only cases when argument is transferred through one 401 /// register. 402 struct ArgRegPair { 403 Register Reg; 404 uint16_t ArgNo; 405 ArgRegPair(Register R, unsigned Arg) : Reg(R), ArgNo(Arg) { 406 assert(Arg < (1 << 16) && "Arg out of range"); 407 } 408 }; 409 /// Vector of call argument and its forwarding register. 410 using CallSiteInfo = SmallVector<ArgRegPair, 1>; 411 using CallSiteInfoImpl = SmallVectorImpl<ArgRegPair>; 412 413 private: 414 Delegate *TheDelegate = nullptr; 415 GISelChangeObserver *Observer = nullptr; 416 417 using CallSiteInfoMap = DenseMap<const MachineInstr *, CallSiteInfo>; 418 /// Map a call instruction to call site arguments forwarding info. 419 CallSiteInfoMap CallSitesInfo; 420 421 /// A helper function that returns call site info for a give call 422 /// instruction if debug entry value support is enabled. 423 CallSiteInfoMap::iterator getCallSiteInfo(const MachineInstr *MI); 424 425 // Callbacks for insertion and removal. 426 void handleInsertion(MachineInstr &MI); 427 void handleRemoval(MachineInstr &MI); 428 friend struct ilist_traits<MachineInstr>; 429 430 public: 431 using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>; 432 VariableDbgInfoMapTy VariableDbgInfos; 433 434 MachineFunction(Function &F, const LLVMTargetMachine &Target, 435 const TargetSubtargetInfo &STI, unsigned FunctionNum, 436 MachineModuleInfo &MMI); 437 MachineFunction(const MachineFunction &) = delete; 438 MachineFunction &operator=(const MachineFunction &) = delete; 439 ~MachineFunction(); 440 441 /// Reset the instance as if it was just created. 442 void reset() { 443 clear(); 444 init(); 445 } 446 447 /// Reset the currently registered delegate - otherwise assert. 448 void resetDelegate(Delegate *delegate) { 449 assert(TheDelegate == delegate && 450 "Only the current delegate can perform reset!"); 451 TheDelegate = nullptr; 452 } 453 454 /// Set the delegate. resetDelegate must be called before attempting 455 /// to set. 456 void setDelegate(Delegate *delegate) { 457 assert(delegate && !TheDelegate && 458 "Attempted to set delegate to null, or to change it without " 459 "first resetting it!"); 460 461 TheDelegate = delegate; 462 } 463 464 void setObserver(GISelChangeObserver *O) { Observer = O; } 465 466 GISelChangeObserver *getObserver() const { return Observer; } 467 468 MachineModuleInfo &getMMI() const { return MMI; } 469 MCContext &getContext() const { return Ctx; } 470 471 /// Returns the Section this function belongs to. 472 MCSection *getSection() const { return Section; } 473 474 /// Indicates the Section this function belongs to. 475 void setSection(MCSection *S) { Section = S; } 476 477 PseudoSourceValueManager &getPSVManager() const { return *PSVManager; } 478 479 /// Return the DataLayout attached to the Module associated to this MF. 480 const DataLayout &getDataLayout() const; 481 482 /// Return the LLVM function that this machine code represents 483 Function &getFunction() { return F; } 484 485 /// Return the LLVM function that this machine code represents 486 const Function &getFunction() const { return F; } 487 488 /// getName - Return the name of the corresponding LLVM function. 489 StringRef getName() const; 490 491 /// getFunctionNumber - Return a unique ID for the current function. 492 unsigned getFunctionNumber() const { return FunctionNumber; } 493 494 /// Returns true if this function has basic block sections enabled. 495 bool hasBBSections() const { 496 return (BBSectionsType == BasicBlockSection::All || 497 BBSectionsType == BasicBlockSection::List); 498 } 499 500 /// Returns true if basic block labels are to be generated for this function. 501 bool hasBBLabels() const { 502 return BBSectionsType == BasicBlockSection::Labels; 503 } 504 505 void setBBSectionsType(BasicBlockSection V) { BBSectionsType = V; } 506 507 /// Creates basic block Labels for this function. 508 void createBBLabels(); 509 510 /// Assign IsBeginSection IsEndSection fields for basic blocks in this 511 /// function. 512 void assignBeginEndSections(); 513 514 /// getTarget - Return the target machine this machine code is compiled with 515 const LLVMTargetMachine &getTarget() const { return Target; } 516 517 /// getSubtarget - Return the subtarget for which this machine code is being 518 /// compiled. 519 const TargetSubtargetInfo &getSubtarget() const { return *STI; } 520 521 /// getSubtarget - This method returns a pointer to the specified type of 522 /// TargetSubtargetInfo. In debug builds, it verifies that the object being 523 /// returned is of the correct type. 524 template<typename STC> const STC &getSubtarget() const { 525 return *static_cast<const STC *>(STI); 526 } 527 528 /// getRegInfo - Return information about the registers currently in use. 529 MachineRegisterInfo &getRegInfo() { return *RegInfo; } 530 const MachineRegisterInfo &getRegInfo() const { return *RegInfo; } 531 532 /// getFrameInfo - Return the frame info object for the current function. 533 /// This object contains information about objects allocated on the stack 534 /// frame of the current function in an abstract way. 535 MachineFrameInfo &getFrameInfo() { return *FrameInfo; } 536 const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; } 537 538 /// getJumpTableInfo - Return the jump table info object for the current 539 /// function. This object contains information about jump tables in the 540 /// current function. If the current function has no jump tables, this will 541 /// return null. 542 const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; } 543 MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; } 544 545 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it 546 /// does already exist, allocate one. 547 MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind); 548 549 /// getConstantPool - Return the constant pool object for the current 550 /// function. 551 MachineConstantPool *getConstantPool() { return ConstantPool; } 552 const MachineConstantPool *getConstantPool() const { return ConstantPool; } 553 554 /// getWasmEHFuncInfo - Return information about how the current function uses 555 /// Wasm exception handling. Returns null for functions that don't use wasm 556 /// exception handling. 557 const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; } 558 WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; } 559 560 /// getWinEHFuncInfo - Return information about how the current function uses 561 /// Windows exception handling. Returns null for functions that don't use 562 /// funclets for exception handling. 563 const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; } 564 WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; } 565 566 /// getAlignment - Return the alignment of the function. 567 Align getAlignment() const { return Alignment; } 568 569 /// setAlignment - Set the alignment of the function. 570 void setAlignment(Align A) { Alignment = A; } 571 572 /// ensureAlignment - Make sure the function is at least A bytes aligned. 573 void ensureAlignment(Align A) { 574 if (Alignment < A) 575 Alignment = A; 576 } 577 578 /// exposesReturnsTwice - Returns true if the function calls setjmp or 579 /// any other similar functions with attribute "returns twice" without 580 /// having the attribute itself. 581 bool exposesReturnsTwice() const { 582 return ExposesReturnsTwice; 583 } 584 585 /// setCallsSetJmp - Set a flag that indicates if there's a call to 586 /// a "returns twice" function. 587 void setExposesReturnsTwice(bool B) { 588 ExposesReturnsTwice = B; 589 } 590 591 /// Returns true if the function contains any inline assembly. 592 bool hasInlineAsm() const { 593 return HasInlineAsm; 594 } 595 596 /// Set a flag that indicates that the function contains inline assembly. 597 void setHasInlineAsm(bool B) { 598 HasInlineAsm = B; 599 } 600 601 bool hasWinCFI() const { 602 return HasWinCFI; 603 } 604 void setHasWinCFI(bool v) { HasWinCFI = v; } 605 606 /// True if this function needs frame moves for debug or exceptions. 607 bool needsFrameMoves() const; 608 609 /// Get the function properties 610 const MachineFunctionProperties &getProperties() const { return Properties; } 611 MachineFunctionProperties &getProperties() { return Properties; } 612 613 /// getInfo - Keep track of various per-function pieces of information for 614 /// backends that would like to do so. 615 /// 616 template<typename Ty> 617 Ty *getInfo() { 618 if (!MFInfo) 619 MFInfo = Ty::template create<Ty>(Allocator, *this); 620 return static_cast<Ty*>(MFInfo); 621 } 622 623 template<typename Ty> 624 const Ty *getInfo() const { 625 return const_cast<MachineFunction*>(this)->getInfo<Ty>(); 626 } 627 628 /// Returns the denormal handling type for the default rounding mode of the 629 /// function. 630 DenormalMode getDenormalMode(const fltSemantics &FPType) const; 631 632 /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they 633 /// are inserted into the machine function. The block number for a machine 634 /// basic block can be found by using the MBB::getNumber method, this method 635 /// provides the inverse mapping. 636 MachineBasicBlock *getBlockNumbered(unsigned N) const { 637 assert(N < MBBNumbering.size() && "Illegal block number"); 638 assert(MBBNumbering[N] && "Block was removed from the machine function!"); 639 return MBBNumbering[N]; 640 } 641 642 /// Should we be emitting segmented stack stuff for the function 643 bool shouldSplitStack() const; 644 645 /// getNumBlockIDs - Return the number of MBB ID's allocated. 646 unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); } 647 648 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and 649 /// recomputes them. This guarantees that the MBB numbers are sequential, 650 /// dense, and match the ordering of the blocks within the function. If a 651 /// specific MachineBasicBlock is specified, only that block and those after 652 /// it are renumbered. 653 void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr); 654 655 /// print - Print out the MachineFunction in a format suitable for debugging 656 /// to the specified stream. 657 void print(raw_ostream &OS, const SlotIndexes* = nullptr) const; 658 659 /// viewCFG - This function is meant for use from the debugger. You can just 660 /// say 'call F->viewCFG()' and a ghostview window should pop up from the 661 /// program, displaying the CFG of the current function with the code for each 662 /// basic block inside. This depends on there being a 'dot' and 'gv' program 663 /// in your path. 664 void viewCFG() const; 665 666 /// viewCFGOnly - This function is meant for use from the debugger. It works 667 /// just like viewCFG, but it does not include the contents of basic blocks 668 /// into the nodes, just the label. If you are only interested in the CFG 669 /// this can make the graph smaller. 670 /// 671 void viewCFGOnly() const; 672 673 /// dump - Print the current MachineFunction to cerr, useful for debugger use. 674 void dump() const; 675 676 /// Run the current MachineFunction through the machine code verifier, useful 677 /// for debugger use. 678 /// \returns true if no problems were found. 679 bool verify(Pass *p = nullptr, const char *Banner = nullptr, 680 bool AbortOnError = true) const; 681 682 // Provide accessors for the MachineBasicBlock list... 683 using iterator = BasicBlockListType::iterator; 684 using const_iterator = BasicBlockListType::const_iterator; 685 using const_reverse_iterator = BasicBlockListType::const_reverse_iterator; 686 using reverse_iterator = BasicBlockListType::reverse_iterator; 687 688 /// Support for MachineBasicBlock::getNextNode(). 689 static BasicBlockListType MachineFunction::* 690 getSublistAccess(MachineBasicBlock *) { 691 return &MachineFunction::BasicBlocks; 692 } 693 694 /// addLiveIn - Add the specified physical register as a live-in value and 695 /// create a corresponding virtual register for it. 696 Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC); 697 698 //===--------------------------------------------------------------------===// 699 // BasicBlock accessor functions. 700 // 701 iterator begin() { return BasicBlocks.begin(); } 702 const_iterator begin() const { return BasicBlocks.begin(); } 703 iterator end () { return BasicBlocks.end(); } 704 const_iterator end () const { return BasicBlocks.end(); } 705 706 reverse_iterator rbegin() { return BasicBlocks.rbegin(); } 707 const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); } 708 reverse_iterator rend () { return BasicBlocks.rend(); } 709 const_reverse_iterator rend () const { return BasicBlocks.rend(); } 710 711 unsigned size() const { return (unsigned)BasicBlocks.size();} 712 bool empty() const { return BasicBlocks.empty(); } 713 const MachineBasicBlock &front() const { return BasicBlocks.front(); } 714 MachineBasicBlock &front() { return BasicBlocks.front(); } 715 const MachineBasicBlock & back() const { return BasicBlocks.back(); } 716 MachineBasicBlock & back() { return BasicBlocks.back(); } 717 718 void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); } 719 void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); } 720 void insert(iterator MBBI, MachineBasicBlock *MBB) { 721 BasicBlocks.insert(MBBI, MBB); 722 } 723 void splice(iterator InsertPt, iterator MBBI) { 724 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI); 725 } 726 void splice(iterator InsertPt, MachineBasicBlock *MBB) { 727 BasicBlocks.splice(InsertPt, BasicBlocks, MBB); 728 } 729 void splice(iterator InsertPt, iterator MBBI, iterator MBBE) { 730 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE); 731 } 732 733 void remove(iterator MBBI) { BasicBlocks.remove(MBBI); } 734 void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); } 735 void erase(iterator MBBI) { BasicBlocks.erase(MBBI); } 736 void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); } 737 738 template <typename Comp> 739 void sort(Comp comp) { 740 BasicBlocks.sort(comp); 741 } 742 743 /// Return the number of \p MachineInstrs in this \p MachineFunction. 744 unsigned getInstructionCount() const { 745 unsigned InstrCount = 0; 746 for (const MachineBasicBlock &MBB : BasicBlocks) 747 InstrCount += MBB.size(); 748 return InstrCount; 749 } 750 751 //===--------------------------------------------------------------------===// 752 // Internal functions used to automatically number MachineBasicBlocks 753 754 /// Adds the MBB to the internal numbering. Returns the unique number 755 /// assigned to the MBB. 756 unsigned addToMBBNumbering(MachineBasicBlock *MBB) { 757 MBBNumbering.push_back(MBB); 758 return (unsigned)MBBNumbering.size()-1; 759 } 760 761 /// removeFromMBBNumbering - Remove the specific machine basic block from our 762 /// tracker, this is only really to be used by the MachineBasicBlock 763 /// implementation. 764 void removeFromMBBNumbering(unsigned N) { 765 assert(N < MBBNumbering.size() && "Illegal basic block #"); 766 MBBNumbering[N] = nullptr; 767 } 768 769 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead 770 /// of `new MachineInstr'. 771 MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL, 772 bool NoImp = false); 773 774 /// Create a new MachineInstr which is a copy of \p Orig, identical in all 775 /// ways except the instruction has no parent, prev, or next. Bundling flags 776 /// are reset. 777 /// 778 /// Note: Clones a single instruction, not whole instruction bundles. 779 /// Does not perform target specific adjustments; consider using 780 /// TargetInstrInfo::duplicate() instead. 781 MachineInstr *CloneMachineInstr(const MachineInstr *Orig); 782 783 /// Clones instruction or the whole instruction bundle \p Orig and insert 784 /// into \p MBB before \p InsertBefore. 785 /// 786 /// Note: Does not perform target specific adjustments; consider using 787 /// TargetInstrInfo::duplicate() intead. 788 MachineInstr &CloneMachineInstrBundle(MachineBasicBlock &MBB, 789 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig); 790 791 /// DeleteMachineInstr - Delete the given MachineInstr. 792 void DeleteMachineInstr(MachineInstr *MI); 793 794 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this 795 /// instead of `new MachineBasicBlock'. 796 MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr); 797 798 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock. 799 void DeleteMachineBasicBlock(MachineBasicBlock *MBB); 800 801 /// getMachineMemOperand - Allocate a new MachineMemOperand. 802 /// MachineMemOperands are owned by the MachineFunction and need not be 803 /// explicitly deallocated. 804 MachineMemOperand *getMachineMemOperand( 805 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 806 Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(), 807 const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System, 808 AtomicOrdering Ordering = AtomicOrdering::NotAtomic, 809 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic); 810 811 /// getMachineMemOperand - Allocate a new MachineMemOperand by copying 812 /// an existing one, adjusting by an offset and using the given size. 813 /// MachineMemOperands are owned by the MachineFunction and need not be 814 /// explicitly deallocated. 815 MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO, 816 int64_t Offset, uint64_t Size); 817 818 /// Allocate a new MachineMemOperand by copying an existing one, 819 /// replacing only AliasAnalysis information. MachineMemOperands are owned 820 /// by the MachineFunction and need not be explicitly deallocated. 821 MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO, 822 const AAMDNodes &AAInfo); 823 824 /// Allocate a new MachineMemOperand by copying an existing one, 825 /// replacing the flags. MachineMemOperands are owned 826 /// by the MachineFunction and need not be explicitly deallocated. 827 MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO, 828 MachineMemOperand::Flags Flags); 829 830 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity; 831 832 /// Allocate an array of MachineOperands. This is only intended for use by 833 /// internal MachineInstr functions. 834 MachineOperand *allocateOperandArray(OperandCapacity Cap) { 835 return OperandRecycler.allocate(Cap, Allocator); 836 } 837 838 /// Dellocate an array of MachineOperands and recycle the memory. This is 839 /// only intended for use by internal MachineInstr functions. 840 /// Cap must be the same capacity that was used to allocate the array. 841 void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) { 842 OperandRecycler.deallocate(Cap, Array); 843 } 844 845 /// Allocate and initialize a register mask with @p NumRegister bits. 846 uint32_t *allocateRegMask(); 847 848 ArrayRef<int> allocateShuffleMask(ArrayRef<int> Mask); 849 850 /// Allocate and construct an extra info structure for a `MachineInstr`. 851 /// 852 /// This is allocated on the function's allocator and so lives the life of 853 /// the function. 854 MachineInstr::ExtraInfo *createMIExtraInfo( 855 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol = nullptr, 856 MCSymbol *PostInstrSymbol = nullptr, MDNode *HeapAllocMarker = nullptr); 857 858 /// Allocate a string and populate it with the given external symbol name. 859 const char *createExternalSymbolName(StringRef Name); 860 861 //===--------------------------------------------------------------------===// 862 // Label Manipulation. 863 864 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table. 865 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 866 /// normal 'L' label is returned. 867 MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx, 868 bool isLinkerPrivate = false) const; 869 870 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC 871 /// base. 872 MCSymbol *getPICBaseSymbol() const; 873 874 /// Returns a reference to a list of cfi instructions in the function's 875 /// prologue. Used to construct frame maps for debug and exception handling 876 /// comsumers. 877 const std::vector<MCCFIInstruction> &getFrameInstructions() const { 878 return FrameInstructions; 879 } 880 881 LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst); 882 883 /// Returns a reference to a list of symbols immediately following calls to 884 /// _setjmp in the function. Used to construct the longjmp target table used 885 /// by Windows Control Flow Guard. 886 const std::vector<MCSymbol *> &getLongjmpTargets() const { 887 return LongjmpTargets; 888 } 889 890 /// Add the specified symbol to the list of valid longjmp targets for Windows 891 /// Control Flow Guard. 892 void addLongjmpTarget(MCSymbol *Target) { LongjmpTargets.push_back(Target); } 893 894 /// \name Exception Handling 895 /// \{ 896 897 bool callsEHReturn() const { return CallsEHReturn; } 898 void setCallsEHReturn(bool b) { CallsEHReturn = b; } 899 900 bool callsUnwindInit() const { return CallsUnwindInit; } 901 void setCallsUnwindInit(bool b) { CallsUnwindInit = b; } 902 903 bool hasEHScopes() const { return HasEHScopes; } 904 void setHasEHScopes(bool V) { HasEHScopes = V; } 905 906 bool hasEHFunclets() const { return HasEHFunclets; } 907 void setHasEHFunclets(bool V) { HasEHFunclets = V; } 908 909 /// Find or create an LandingPadInfo for the specified MachineBasicBlock. 910 LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad); 911 912 /// Remap landing pad labels and remove any deleted landing pads. 913 void tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap = nullptr, 914 bool TidyIfNoBeginLabels = true); 915 916 /// Return a reference to the landing pad info for the current function. 917 const std::vector<LandingPadInfo> &getLandingPads() const { 918 return LandingPads; 919 } 920 921 /// Provide the begin and end labels of an invoke style call and associate it 922 /// with a try landing pad block. 923 void addInvoke(MachineBasicBlock *LandingPad, 924 MCSymbol *BeginLabel, MCSymbol *EndLabel); 925 926 /// Add a new panding pad, and extract the exception handling information from 927 /// the landingpad instruction. Returns the label ID for the landing pad 928 /// entry. 929 MCSymbol *addLandingPad(MachineBasicBlock *LandingPad); 930 931 /// Provide the catch typeinfo for a landing pad. 932 void addCatchTypeInfo(MachineBasicBlock *LandingPad, 933 ArrayRef<const GlobalValue *> TyInfo); 934 935 /// Provide the filter typeinfo for a landing pad. 936 void addFilterTypeInfo(MachineBasicBlock *LandingPad, 937 ArrayRef<const GlobalValue *> TyInfo); 938 939 /// Add a cleanup action for a landing pad. 940 void addCleanup(MachineBasicBlock *LandingPad); 941 942 void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter, 943 const BlockAddress *RecoverBA); 944 945 void addSEHCleanupHandler(MachineBasicBlock *LandingPad, 946 const Function *Cleanup); 947 948 /// Return the type id for the specified typeinfo. This is function wide. 949 unsigned getTypeIDFor(const GlobalValue *TI); 950 951 /// Return the id of the filter encoded by TyIds. This is function wide. 952 int getFilterIDFor(std::vector<unsigned> &TyIds); 953 954 /// Map the landing pad's EH symbol to the call site indexes. 955 void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites); 956 957 /// Map the landing pad to its index. Used for Wasm exception handling. 958 void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) { 959 WasmLPadToIndexMap[LPad] = Index; 960 } 961 962 /// Returns true if the landing pad has an associate index in wasm EH. 963 bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const { 964 return WasmLPadToIndexMap.count(LPad); 965 } 966 967 /// Get the index in wasm EH for a given landing pad. 968 unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const { 969 assert(hasWasmLandingPadIndex(LPad)); 970 return WasmLPadToIndexMap.lookup(LPad); 971 } 972 973 /// Get the call site indexes for a landing pad EH symbol. 974 SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) { 975 assert(hasCallSiteLandingPad(Sym) && 976 "missing call site number for landing pad!"); 977 return LPadToCallSiteMap[Sym]; 978 } 979 980 /// Return true if the landing pad Eh symbol has an associated call site. 981 bool hasCallSiteLandingPad(MCSymbol *Sym) { 982 return !LPadToCallSiteMap[Sym].empty(); 983 } 984 985 /// Map the begin label for a call site. 986 void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) { 987 CallSiteMap[BeginLabel] = Site; 988 } 989 990 /// Get the call site number for a begin label. 991 unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const { 992 assert(hasCallSiteBeginLabel(BeginLabel) && 993 "Missing call site number for EH_LABEL!"); 994 return CallSiteMap.lookup(BeginLabel); 995 } 996 997 /// Return true if the begin label has a call site number associated with it. 998 bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const { 999 return CallSiteMap.count(BeginLabel); 1000 } 1001 1002 /// Record annotations associated with a particular label. 1003 void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) { 1004 CodeViewAnnotations.push_back({Label, MD}); 1005 } 1006 1007 ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const { 1008 return CodeViewAnnotations; 1009 } 1010 1011 /// Return a reference to the C++ typeinfo for the current function. 1012 const std::vector<const GlobalValue *> &getTypeInfos() const { 1013 return TypeInfos; 1014 } 1015 1016 /// Return a reference to the typeids encoding filters used in the current 1017 /// function. 1018 const std::vector<unsigned> &getFilterIds() const { 1019 return FilterIds; 1020 } 1021 1022 /// \} 1023 1024 /// Collect information used to emit debugging information of a variable. 1025 void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, 1026 int Slot, const DILocation *Loc) { 1027 VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc); 1028 } 1029 1030 VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; } 1031 const VariableDbgInfoMapTy &getVariableDbgInfo() const { 1032 return VariableDbgInfos; 1033 } 1034 1035 /// Start tracking the arguments passed to the call \p CallI. 1036 void addCallArgsForwardingRegs(const MachineInstr *CallI, 1037 CallSiteInfoImpl &&CallInfo) { 1038 assert(CallI->isCandidateForCallSiteEntry()); 1039 bool Inserted = 1040 CallSitesInfo.try_emplace(CallI, std::move(CallInfo)).second; 1041 (void)Inserted; 1042 assert(Inserted && "Call site info not unique"); 1043 } 1044 1045 const CallSiteInfoMap &getCallSitesInfo() const { 1046 return CallSitesInfo; 1047 } 1048 1049 /// Following functions update call site info. They should be called before 1050 /// removing, replacing or copying call instruction. 1051 1052 /// Erase the call site info for \p MI. It is used to remove a call 1053 /// instruction from the instruction stream. 1054 void eraseCallSiteInfo(const MachineInstr *MI); 1055 /// Copy the call site info from \p Old to \ New. Its usage is when we are 1056 /// making a copy of the instruction that will be inserted at different point 1057 /// of the instruction stream. 1058 void copyCallSiteInfo(const MachineInstr *Old, 1059 const MachineInstr *New); 1060 1061 const std::vector<char> &getBBSectionsSymbolPrefix() const { 1062 return BBSectionsSymbolPrefix; 1063 } 1064 1065 /// Move the call site info from \p Old to \New call site info. This function 1066 /// is used when we are replacing one call instruction with another one to 1067 /// the same callee. 1068 void moveCallSiteInfo(const MachineInstr *Old, 1069 const MachineInstr *New); 1070 }; 1071 1072 //===--------------------------------------------------------------------===// 1073 // GraphTraits specializations for function basic block graphs (CFGs) 1074 //===--------------------------------------------------------------------===// 1075 1076 // Provide specializations of GraphTraits to be able to treat a 1077 // machine function as a graph of machine basic blocks... these are 1078 // the same as the machine basic block iterators, except that the root 1079 // node is implicitly the first node of the function. 1080 // 1081 template <> struct GraphTraits<MachineFunction*> : 1082 public GraphTraits<MachineBasicBlock*> { 1083 static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); } 1084 1085 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph 1086 using nodes_iterator = pointer_iterator<MachineFunction::iterator>; 1087 1088 static nodes_iterator nodes_begin(MachineFunction *F) { 1089 return nodes_iterator(F->begin()); 1090 } 1091 1092 static nodes_iterator nodes_end(MachineFunction *F) { 1093 return nodes_iterator(F->end()); 1094 } 1095 1096 static unsigned size (MachineFunction *F) { return F->size(); } 1097 }; 1098 template <> struct GraphTraits<const MachineFunction*> : 1099 public GraphTraits<const MachineBasicBlock*> { 1100 static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); } 1101 1102 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph 1103 using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>; 1104 1105 static nodes_iterator nodes_begin(const MachineFunction *F) { 1106 return nodes_iterator(F->begin()); 1107 } 1108 1109 static nodes_iterator nodes_end (const MachineFunction *F) { 1110 return nodes_iterator(F->end()); 1111 } 1112 1113 static unsigned size (const MachineFunction *F) { 1114 return F->size(); 1115 } 1116 }; 1117 1118 // Provide specializations of GraphTraits to be able to treat a function as a 1119 // graph of basic blocks... and to walk it in inverse order. Inverse order for 1120 // a function is considered to be when traversing the predecessor edges of a BB 1121 // instead of the successor edges. 1122 // 1123 template <> struct GraphTraits<Inverse<MachineFunction*>> : 1124 public GraphTraits<Inverse<MachineBasicBlock*>> { 1125 static NodeRef getEntryNode(Inverse<MachineFunction *> G) { 1126 return &G.Graph->front(); 1127 } 1128 }; 1129 template <> struct GraphTraits<Inverse<const MachineFunction*>> : 1130 public GraphTraits<Inverse<const MachineBasicBlock*>> { 1131 static NodeRef getEntryNode(Inverse<const MachineFunction *> G) { 1132 return &G.Graph->front(); 1133 } 1134 }; 1135 1136 } // end namespace llvm 1137 1138 #endif // LLVM_CODEGEN_MACHINEFUNCTION_H 1139