LLVM  9.0.0svn
GlobalSplit.cpp
Go to the documentation of this file.
1 //===- GlobalSplit.cpp - global variable splitter -------------------------===//
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 pass uses inrange annotations on GEP indices to split globals where
10 // beneficial. Clang currently attaches these annotations to references to
11 // virtual table globals under the Itanium ABI for the benefit of the
12 // whole-program virtual call optimization and control flow integrity passes.
13 //
14 //===----------------------------------------------------------------------===//
15 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalValue.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/User.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Transforms/IPO.h"
35 #include <cstdint>
36 #include <vector>
37 
38 using namespace llvm;
39 
40 static bool splitGlobal(GlobalVariable &GV) {
41  // If the address of the global is taken outside of the module, we cannot
42  // apply this transformation.
43  if (!GV.hasLocalLinkage())
44  return false;
45 
46  // We currently only know how to split ConstantStructs.
47  auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
48  if (!Init)
49  return false;
50 
51  // Verify that each user of the global is an inrange getelementptr constant.
52  // From this it follows that any loads from or stores to that global must use
53  // a pointer derived from an inrange getelementptr constant, which is
54  // sufficient to allow us to apply the splitting transform.
55  for (User *U : GV.users()) {
56  if (!isa<Constant>(U))
57  return false;
58 
59  auto *GEP = dyn_cast<GEPOperator>(U);
60  if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
61  !isa<ConstantInt>(GEP->getOperand(1)) ||
62  !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
63  !isa<ConstantInt>(GEP->getOperand(2)))
64  return false;
65  }
66 
69 
70  const DataLayout &DL = GV.getParent()->getDataLayout();
71  const StructLayout *SL = DL.getStructLayout(Init->getType());
72 
74 
75  std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
76  for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
77  // Build a global representing this split piece.
78  auto *SplitGV =
79  new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
81  Init->getOperand(I), GV.getName() + "." + utostr(I));
82  SplitGlobals[I] = SplitGV;
83 
84  unsigned SplitBegin = SL->getElementOffset(I);
85  unsigned SplitEnd = (I == Init->getNumOperands() - 1)
86  ? SL->getSizeInBytes()
87  : SL->getElementOffset(I + 1);
88 
89  // Rebuild type metadata, adjusting by the split offset.
90  // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
91  for (MDNode *Type : Types) {
92  uint64_t ByteOffset = cast<ConstantInt>(
93  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
94  ->getZExtValue();
95  // Type metadata may be attached one byte after the end of the vtable, for
96  // classes without virtual methods in Itanium ABI. AFAIK, it is never
97  // attached to the first byte of a vtable. Subtract one to get the right
98  // slice.
99  // This is making an assumption that vtable groups are the only kinds of
100  // global variables that !type metadata can be attached to, and that they
101  // are either Itanium ABI vtable groups or contain a single vtable (i.e.
102  // Microsoft ABI vtables).
103  uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
104  if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
105  continue;
106  SplitGV->addMetadata(
108  *MDNode::get(GV.getContext(),
110  ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
111  Type->getOperand(1)}));
112  }
113  }
114 
115  for (User *U : GV.users()) {
116  auto *GEP = cast<GEPOperator>(U);
117  unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
118  if (I >= SplitGlobals.size())
119  continue;
120 
122  Ops.push_back(ConstantInt::get(Int32Ty, 0));
123  for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
124  Ops.push_back(GEP->getOperand(I));
125 
126  auto *NewGEP = ConstantExpr::getGetElementPtr(
127  SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
128  GEP->isInBounds());
129  GEP->replaceAllUsesWith(NewGEP);
130  }
131 
132  // Finally, remove the original global. Any remaining uses refer to invalid
133  // elements of the global, so replace with undef.
134  if (!GV.use_empty())
136  GV.eraseFromParent();
137  return true;
138 }
139 
140 static bool splitGlobals(Module &M) {
141  // First, see if the module uses either of the llvm.type.test or
142  // llvm.type.checked.load intrinsics, which indicates that splitting globals
143  // may be beneficial.
144  Function *TypeTestFunc =
145  M.getFunction(Intrinsic::getName(Intrinsic::type_test));
146  Function *TypeCheckedLoadFunc =
147  M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
148  if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
149  (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
150  return false;
151 
152  bool Changed = false;
153  for (auto I = M.global_begin(); I != M.global_end();) {
154  GlobalVariable &GV = *I;
155  ++I;
156  Changed |= splitGlobal(GV);
157  }
158  return Changed;
159 }
160 
161 namespace {
162 
163 struct GlobalSplit : public ModulePass {
164  static char ID;
165 
166  GlobalSplit() : ModulePass(ID) {
168  }
169 
170  bool runOnModule(Module &M) override {
171  if (skipModule(M))
172  return false;
173 
174  return splitGlobals(M);
175  }
176 };
177 
178 } // end anonymous namespace
179 
180 char GlobalSplit::ID = 0;
181 
182 INITIALIZE_PASS(GlobalSplit, "globalsplit", "Global splitter", false, false)
183 
185  return new GlobalSplit;
186 }
187 
189  if (!splitGlobals(M))
190  return PreservedAnalyses::all();
191  return PreservedAnalyses::none();
192 }
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1153
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:607
This file contains the declarations for metadata subclasses.
void initializeGlobalSplitPass(PassRegistry &)
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:709
Metadata node.
Definition: Metadata.h:863
Hexagon Common GEP
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:554
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:625
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1443
static bool splitGlobals(Module &M)
global_iterator global_begin()
Definition: Module.h:581
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:409
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Globals.cpp:358
Class to represent integer types.
Definition: DerivedTypes.h:39
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1424
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static wasm::ValType getType(const TargetRegisterClass *RC)
ModulePass * createGlobalSplitPass()
This pass splits globals into pieces for the benefit of whole-program devirtualization and control-fl...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
global_iterator global_end()
Definition: Module.h:583
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
Module.h This file contains the declarations for the Module class.
uint64_t getSizeInBytes() const
Definition: DataLayout.h:562
static Constant * getInitializer(Constant *C)
Definition: Evaluator.cpp:177
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:631
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:174
iterator_range< user_iterator > users()
Definition: Value.h:399
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:545
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:576
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
#define I(x, y, z)
Definition: MD5.cpp:58
static bool splitGlobal(GlobalVariable &GV)
Definition: GlobalSplit.cpp:40
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
A container for analyses that lazily runs them and caches their results.
bool use_empty() const
Definition: Value.h:322
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
IntegerType * Int32Ty