File: ms-cxx-helper.cpp

package info (click to toggle)
ldc 1%3A1.30.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 59,248 kB
  • sloc: cpp: 61,598; ansic: 14,545; sh: 1,014; makefile: 972; asm: 510; objc: 135; exp: 48; python: 12
file content (197 lines) | stat: -rw-r--r-- 7,266 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//===-- ms-cxx-helper.cpp -------------------------------------------------===//
//
//                         LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//

#include "gen/ms-cxx-helper.h"

#include "dmd/target.h"
#include "gen/irstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/mangling.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/CFG.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Cloning.h"

llvm::BasicBlock *getUnwindDest(llvm::Instruction *I) {
  if (auto II = llvm::dyn_cast<llvm::InvokeInst>(I))
    return II->getUnwindDest();
  if (auto CSI = llvm::dyn_cast<llvm::CatchSwitchInst>(I))
    return CSI->getUnwindDest();
  if (auto CRPI = llvm::dyn_cast<llvm::CleanupReturnInst>(I))
    return CRPI->getUnwindDest();
  return nullptr;
}

// return all basic blocks that are reachable from bb, but don't pass through
// ebb and don't follow unwinding target
void findSuccessors(std::vector<llvm::BasicBlock *> &blocks,
                    llvm::BasicBlock *bb, llvm::BasicBlock *ebb) {
  blocks.push_back(bb);
  if (bb != ebb) {
    assert(bb->getTerminator());
    for (size_t pos = 0; pos < blocks.size(); ++pos) {
      bb = blocks[pos];
      if (auto term = bb->getTerminator()) {
        llvm::BasicBlock *unwindDest = getUnwindDest(term);
        unsigned cnt = term->getNumSuccessors();
        for (unsigned s = 0; s < cnt; s++) {
          llvm::BasicBlock *succ = term->getSuccessor(s);
          if (succ != ebb && succ != unwindDest &&
              std::find(blocks.begin(), blocks.end(), succ) == blocks.end()) {
            blocks.push_back(succ);
          }
        }
      }
    }
    blocks.push_back(ebb);
  }
}

// remap values in all instructions of all blocks
void remapBlocks(std::vector<llvm::BasicBlock *> &blocks,
                 llvm::ValueToValueMapTy &VMap) {
  for (llvm::BasicBlock *bb : blocks)
    for (auto &I : *bb) {
      llvm::RemapInstruction(&I, VMap,
                             llvm::RF_IgnoreMissingLocals |
                                 llvm::RF_NoModuleLevelChanges);
    }
}

void remapBlocksValue(std::vector<llvm::BasicBlock *> &blocks,
                      llvm::Value *from, llvm::Value *to) {
  llvm::ValueToValueMapTy VMap;
  VMap[from] = to;
  remapBlocks(blocks, VMap);
}

// make a copy of all blocks and instructions in srcblocks
// - map values to clones
// - redirect srcTarget to continueWith
// - set "funclet" attribute inside catch/cleanup pads
// - inside funclets, replace "unreachable" with "branch cleanupret"
void cloneBlocks(const std::vector<llvm::BasicBlock *> &srcblocks,
                 std::vector<llvm::BasicBlock *> &blocks,
                 llvm::BasicBlock *continueWith, llvm::BasicBlock *unwindTo,
                 llvm::Value *funclet) {
  llvm::ValueToValueMapTy VMap;
  // map the terminal branch to the new target
  if (continueWith)
    if (auto term = srcblocks.back()->getTerminator())
      if (auto succ = term->getSuccessor(0))
        VMap[succ] = continueWith;

  for (auto bb : srcblocks) {
    llvm::Function *F = bb->getParent();

    auto nbb = llvm::BasicBlock::Create(bb->getContext(), bb->getName());
    // Loop over all instructions, and copy them over.
    for (auto &II : *bb) {
      llvm::Instruction *Inst = &II;
      llvm::Instruction *newInst = nullptr;
      if (funclet &&
          !llvm::isa<llvm::DbgInfoIntrinsic>(Inst)) { // IntrinsicInst?
        if (auto IInst = llvm::dyn_cast<llvm::InvokeInst>(Inst)) {
          auto invoke = llvm::InvokeInst::Create(
              IInst, llvm::OperandBundleDef("funclet", funclet));
          newInst = invoke;
        } else if (auto CInst = llvm::dyn_cast<llvm::CallInst>(Inst)) {
          auto call = llvm::CallInst::Create(
              CInst, llvm::OperandBundleDef("funclet", funclet));
          newInst = call;
        } else if (funclet && llvm::isa<llvm::UnreachableInst>(Inst)) {
          newInst = llvm::BranchInst::Create(continueWith); // to cleanupret
        }
      }
      if (!newInst)
        newInst = Inst->clone();

      nbb->getInstList().push_back(newInst);
      VMap[Inst] = newInst; // Add instruction map to value.
      if (unwindTo)
        if (auto dest = getUnwindDest(Inst))
          VMap[dest] = unwindTo;
    }
    nbb->insertInto(F, continueWith);
    VMap[bb] = nbb;
    blocks.push_back(nbb);
  }

  remapBlocks(blocks, VMap);
}

bool isCatchSwitchBlock(llvm::BasicBlock *bb) {
  if (bb->empty())
    return false;
  return llvm::dyn_cast<llvm::CatchSwitchInst>(&bb->front());
}

// copy from clang/.../MicrosoftCXXABI.cpp

// routines for constructing the llvm types for MS RTTI structs.
llvm::StructType *getTypeDescriptorType(IRState &irs,
                                        llvm::Constant *classInfoPtr,
                                        llvm::StringRef TypeInfoString) {
  llvm::SmallString<256> TDTypeName("rtti.TypeDescriptor");
  TDTypeName += llvm::utostr(TypeInfoString.size());
  llvm::StructType *&TypeDescriptorType =
      irs.TypeDescriptorTypeMap[TypeInfoString.size()];
  if (TypeDescriptorType)
    return TypeDescriptorType;
  auto int8Ty = LLType::getInt8Ty(gIR->context());
  llvm::Type *FieldTypes[] = {
      classInfoPtr->getType(), // CGM.Int8PtrPtrTy,
      getPtrToType(int8Ty),    // CGM.Int8PtrTy,
      llvm::ArrayType::get(int8Ty, TypeInfoString.size() + 1)};
  TypeDescriptorType =
      llvm::StructType::create(gIR->context(), FieldTypes, TDTypeName);
  return TypeDescriptorType;
}

llvm::GlobalVariable *getTypeDescriptor(IRState &irs, ClassDeclaration *cd) {
  if (cd->isCPPclass()) {
    const char *name = target.cpp.typeInfoMangle(cd);
    return declareGlobal(cd->loc, irs.module, getVoidPtrType(), name,
                         /*isConstant*/ true, false,
                         /*useDLLImport*/ cd->isExport());
  }

  llvm::GlobalVariable *&Var = irs.TypeDescriptorMap[cd];
  if (Var)
    return Var;

  auto classInfoPtr = getIrAggr(cd, true)->getClassInfoSymbol();

  // The type name must match the expectation in druntime's ldc.eh_msvc - the
  // TypeInfo_Class name with a 'D' prefix (the first character is skipped in
  // debugger output).
  const auto TypeNameString =
      (llvm::Twine("D") + cd->toPrettyChars(/*QualifyTypes=*/true)).str();

  const auto TypeDescName = getIRMangledAggregateName(cd, "@TypeDescriptor");

  // Declare and initialize the TypeDescriptor.
  llvm::Constant *Fields[] = {
      classInfoPtr, // VFPtr
      llvm::ConstantPointerNull::get(
          LLType::getInt8PtrTy(gIR->context())), // Runtime data
      llvm::ConstantDataArray::getString(gIR->context(), TypeNameString)};
  llvm::StructType *TypeDescriptorType =
      getTypeDescriptorType(irs, classInfoPtr, TypeNameString);

  const LinkageWithCOMDAT lwc = {LLGlobalVariable::LinkOnceODRLinkage, true};
  Var = defineGlobal(cd->loc, gIR->module, TypeDescName,
                     llvm::ConstantStruct::get(TypeDescriptorType, Fields),
                     lwc.first, /*isConstant=*/true);
  setLinkage(lwc, Var);

  return Var;
}