LLVM  8.0.1
GlobalSplit.cpp
Go to the documentation of this file.
1 //===- GlobalSplit.cpp - global variable splitter -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/User.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Transforms/IPO.h"
36 #include <cstdint>
37 #include <vector>
38 
39 using namespace llvm;
40 
41 static bool splitGlobal(GlobalVariable &GV) {
42  // If the address of the global is taken outside of the module, we cannot
43  // apply this transformation.
44  if (!GV.hasLocalLinkage())
45  return false;
46 
47  // We currently only know how to split ConstantStructs.
48  auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
49  if (!Init)
50  return false;
51 
52  // Verify that each user of the global is an inrange getelementptr constant.
53  // From this it follows that any loads from or stores to that global must use
54  // a pointer derived from an inrange getelementptr constant, which is
55  // sufficient to allow us to apply the splitting transform.
56  for (User *U : GV.users()) {
57  if (!isa<Constant>(U))
58  return false;
59 
60  auto *GEP = dyn_cast<GEPOperator>(U);
61  if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
62  !isa<ConstantInt>(GEP->getOperand(1)) ||
63  !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
64  !isa<ConstantInt>(GEP->getOperand(2)))
65  return false;
66  }
67 
70 
71  const DataLayout &DL = GV.getParent()->getDataLayout();
72  const StructLayout *SL = DL.getStructLayout(Init->getType());
73 
75 
76  std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
77  for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
78  // Build a global representing this split piece.
79  auto *SplitGV =
80  new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
82  Init->getOperand(I), GV.getName() + "." + utostr(I));
83  SplitGlobals[I] = SplitGV;
84 
85  unsigned SplitBegin = SL->getElementOffset(I);
86  unsigned SplitEnd = (I == Init->getNumOperands() - 1)
87  ? SL->getSizeInBytes()
88  : SL->getElementOffset(I + 1);
89 
90  // Rebuild type metadata, adjusting by the split offset.
91  // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
92  for (MDNode *Type : Types) {
93  uint64_t ByteOffset = cast<ConstantInt>(
94  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
95  ->getZExtValue();
96  // Type metadata may be attached one byte after the end of the vtable, for
97  // classes without virtual methods in Itanium ABI. AFAIK, it is never
98  // attached to the first byte of a vtable. Subtract one to get the right
99  // slice.
100  // This is making an assumption that vtable groups are the only kinds of
101  // global variables that !type metadata can be attached to, and that they
102  // are either Itanium ABI vtable groups or contain a single vtable (i.e.
103  // Microsoft ABI vtables).
104  uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
105  if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
106  continue;
107  SplitGV->addMetadata(
109  *MDNode::get(GV.getContext(),
111  ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
112  Type->getOperand(1)}));
113  }
114  }
115 
116  for (User *U : GV.users()) {
117  auto *GEP = cast<GEPOperator>(U);
118  unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
119  if (I >= SplitGlobals.size())
120  continue;
121 
123  Ops.push_back(ConstantInt::get(Int32Ty, 0));
124  for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
125  Ops.push_back(GEP->getOperand(I));
126 
127  auto *NewGEP = ConstantExpr::getGetElementPtr(
128  SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
129  GEP->isInBounds());
130  GEP->replaceAllUsesWith(NewGEP);
131  }
132 
133  // Finally, remove the original global. Any remaining uses refer to invalid
134  // elements of the global, so replace with undef.
135  if (!GV.use_empty())
137  GV.eraseFromParent();
138  return true;
139 }
140 
141 static bool splitGlobals(Module &M) {
142  // First, see if the module uses either of the llvm.type.test or
143  // llvm.type.checked.load intrinsics, which indicates that splitting globals
144  // may be beneficial.
145  Function *TypeTestFunc =
147  Function *TypeCheckedLoadFunc =
149  if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
150  (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
151  return false;
152 
153  bool Changed = false;
154  for (auto I = M.global_begin(); I != M.global_end();) {
155  GlobalVariable &GV = *I;
156  ++I;
157  Changed |= splitGlobal(GV);
158  }
159  return Changed;
160 }
161 
162 namespace {
163 
164 struct GlobalSplit : public ModulePass {
165  static char ID;
166 
167  GlobalSplit() : ModulePass(ID) {
169  }
170 
171  bool runOnModule(Module &M) override {
172  if (skipModule(M))
173  return false;
174 
175  return splitGlobals(M);
176  }
177 };
178 
179 } // end anonymous namespace
180 
181 char GlobalSplit::ID = 0;
182 
183 INITIALIZE_PASS(GlobalSplit, "globalsplit", "Global splitter", false, false)
184 
186  return new GlobalSplit;
187 }
188 
190  if (!splitGlobals(M))
191  return PreservedAnalyses::all();
192  return PreservedAnalyses::none();
193 }
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
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:24
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:1154
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:588
This file contains the declarations for metadata subclasses.
void initializeGlobalSplitPass(PassRegistry &)
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
Metadata node.
Definition: Metadata.h:864
Hexagon Common GEP
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:529
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:626
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
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:1444
static bool splitGlobals(Module &M)
global_iterator global_begin()
Definition: Module.h:578
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:410
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1166
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
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:359
Class to represent integer types.
Definition: DerivedTypes.h:40
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1415
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
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:34
global_iterator global_end()
Definition: Module.h:580
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
uint64_t getSizeInBytes() const
Definition: DataLayout.h:537
static Constant * getInitializer(Constant *C)
Definition: Evaluator.cpp:178
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:622
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:224
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:176
iterator_range< user_iterator > users()
Definition: Value.h:400
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:546
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:551
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
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:41
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
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:323
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
A container for analyses that lazily runs them and caches their results.
bool use_empty() const
Definition: Value.h:323
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:274
IntegerType * Int32Ty