Emit Globals in AsmPrinter

Reference

The call path of emitting a global variable:

AsmPrinter::doFinalization(Module &)
=> emitGlobalVariable(&G); // for (const auto &G : M.globals())
=> emitGlobalGOTEquivs()
   => emitGlobalVariable(GV) // for (auto *GV: FailedCandidates)

Function interfaces for global emission in AsmPrinter:

// llvm/include/llvm/CodeGen/AsmPrinter.h

/// This class is intended to be used as a driving class for all asm writers.
class AsmPrinter : public MachineFunctionPass {
  ...
  /// Emit the specified global variable to the .s file.
  virtual void emitGlobalVariable(const GlobalVariable *GV);

  /// Check to see if the specified global is a special global used by LLVM. If
  /// so, emit it and return true, otherwise do nothing and return false.
  bool emitSpecialLLVMGlobal(const GlobalVariable *GV);

  /// Constant expressions using GOT equivalent globals may not be
  /// eligible for PC relative GOT entry conversion, in such cases we need to
  /// emit the proxies we previously omitted in EmitGlobalVariable.
  void emitGlobalGOTEquivs();
  ...
}

// llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

static void emitGlobalConstantArray(const DataLayout &DL,
                                    const ConstantArray *CA, AsmPrinter &AP,
                                    const Constant *BaseCV, uint64_t Offset);

static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
                                   AsmPrinter &AP,
                                   const Constant *BaseCV = nullptr,
                                   uint64_t Offset = 0);

static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);

The global variable value is finally emitted by EmitGlobalConstant:

/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV,
                                    uint64_t TailPadding) {
  uint64_t Size = DL.getTypeAllocSize(CV->getType());
  if (Size)
    emitGlobalConstantImpl(DL, CV, *this);
  else if (MAI->hasSubsectionsViaSymbols()) {
    // If the global has zero size, emit a single byte so that two labels don't
    // look like they are at the same location.
    OutStreamer->EmitIntValue(0, 1);
  }
  if (TailPadding != 0) {
    OutStreamer->AddComment("Tail padding to ensure precise bounds");
    OutStreamer->EmitZeros(TailPadding);
  }
}
Created Jul 26, 2020 // Last Updated Aug 29, 2020

If you could revise
the fundmental principles of
computer system design
to improve security...

... what would you change?