1 //===- GlobalSplit.cpp - global variable splitter -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass uses inrange annotations on GEP indices to split globals where
11 // beneficial. Clang currently attaches these annotations to references to
12 // virtual table globals under the Itanium ABI for the benefit of the
13 // whole-program virtual call optimization and control flow integrity passes.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/Transforms/IPO/GlobalSplit.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Intrinsics.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Pass.h"
33 bool splitGlobal(GlobalVariable &GV) {
34 // If the address of the global is taken outside of the module, we cannot
35 // apply this transformation.
36 if (!GV.hasLocalLinkage())
39 // We currently only know how to split ConstantStructs.
40 auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
44 // Verify that each user of the global is an inrange getelementptr constant.
45 // From this it follows that any loads from or stores to that global must use
46 // a pointer derived from an inrange getelementptr constant, which is
47 // sufficient to allow us to apply the splitting transform.
48 for (User *U : GV.users()) {
49 if (!isa<Constant>(U))
52 auto *GEP = dyn_cast<GEPOperator>(U);
53 if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
54 !isa<ConstantInt>(GEP->getOperand(1)) ||
55 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
56 !isa<ConstantInt>(GEP->getOperand(2)))
60 SmallVector<MDNode *, 2> Types;
61 GV.getMetadata(LLVMContext::MD_type, Types);
63 const DataLayout &DL = GV.getParent()->getDataLayout();
64 const StructLayout *SL = DL.getStructLayout(Init->getType());
66 IntegerType *Int32Ty = Type::getInt32Ty(GV.getContext());
68 std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
69 for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
70 // Build a global representing this split piece.
72 new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
73 GV.isConstant(), GlobalValue::PrivateLinkage,
74 Init->getOperand(I), GV.getName() + "." + utostr(I));
75 SplitGlobals[I] = SplitGV;
77 unsigned SplitBegin = SL->getElementOffset(I);
78 unsigned SplitEnd = (I == Init->getNumOperands() - 1)
79 ? SL->getSizeInBytes()
80 : SL->getElementOffset(I + 1);
82 // Rebuild type metadata, adjusting by the split offset.
83 // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
84 for (MDNode *Type : Types) {
85 uint64_t ByteOffset = cast<ConstantInt>(
86 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
88 // Type metadata may be attached one byte after the end of the vtable, for
89 // classes without virtual methods in Itanium ABI. AFAIK, it is never
90 // attached to the first byte of a vtable. Subtract one to get the right
92 // This is making an assumption that vtable groups are the only kinds of
93 // global variables that !type metadata can be attached to, and that they
94 // are either Itanium ABI vtable groups or contain a single vtable (i.e.
95 // Microsoft ABI vtables).
96 uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
97 if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
100 LLVMContext::MD_type,
101 *MDNode::get(GV.getContext(),
102 {ConstantAsMetadata::get(
103 ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
104 Type->getOperand(1)}));
108 for (User *U : GV.users()) {
109 auto *GEP = cast<GEPOperator>(U);
110 unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
111 if (I >= SplitGlobals.size())
114 SmallVector<Value *, 4> Ops;
115 Ops.push_back(ConstantInt::get(Int32Ty, 0));
116 for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
117 Ops.push_back(GEP->getOperand(I));
119 auto *NewGEP = ConstantExpr::getGetElementPtr(
120 SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
122 GEP->replaceAllUsesWith(NewGEP);
125 // Finally, remove the original global. Any remaining uses refer to invalid
126 // elements of the global, so replace with undef.
128 GV.replaceAllUsesWith(UndefValue::get(GV.getType()));
129 GV.eraseFromParent();
133 bool splitGlobals(Module &M) {
134 // First, see if the module uses either of the llvm.type.test or
135 // llvm.type.checked.load intrinsics, which indicates that splitting globals
136 // may be beneficial.
137 Function *TypeTestFunc =
138 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
139 Function *TypeCheckedLoadFunc =
140 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
141 if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
142 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
145 bool Changed = false;
146 for (auto I = M.global_begin(); I != M.global_end();) {
147 GlobalVariable &GV = *I;
149 Changed |= splitGlobal(GV);
154 struct GlobalSplit : public ModulePass {
156 GlobalSplit() : ModulePass(ID) {
157 initializeGlobalSplitPass(*PassRegistry::getPassRegistry());
159 bool runOnModule(Module &M) {
163 return splitGlobals(M);
169 INITIALIZE_PASS(GlobalSplit, "globalsplit", "Global splitter", false, false)
170 char GlobalSplit::ID = 0;
172 ModulePass *llvm::createGlobalSplitPass() {
173 return new GlobalSplit;
176 PreservedAnalyses GlobalSplitPass::run(Module &M, ModuleAnalysisManager &AM) {
177 if (!splitGlobals(M))
178 return PreservedAnalyses::all();
179 return PreservedAnalyses::none();