LLVM 19.0.0git
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
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"
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"
33#include "llvm/Transforms/IPO.h"
34#include <cstdint>
35#include <vector>
36
37using namespace llvm;
38
39static bool splitGlobal(GlobalVariable &GV) {
40 // If the address of the global is taken outside of the module, we cannot
41 // apply this transformation.
42 if (!GV.hasLocalLinkage())
43 return false;
44
45 // We currently only know how to split ConstantStructs.
46 auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
47 if (!Init)
48 return false;
49
50 const DataLayout &DL = GV.getParent()->getDataLayout();
51 const StructLayout *SL = DL.getStructLayout(Init->getType());
52 ArrayRef<TypeSize> MemberOffsets = SL->getMemberOffsets();
53 unsigned IndexWidth = DL.getIndexTypeSizeInBits(GV.getType());
54
55 // Verify that each user of the global is an inrange getelementptr constant,
56 // and collect information on how it relates to the global.
57 struct GEPInfo {
59 unsigned MemberIndex;
60 APInt MemberRelativeOffset;
61
62 GEPInfo(GEPOperator *GEP, unsigned MemberIndex, APInt MemberRelativeOffset)
63 : GEP(GEP), MemberIndex(MemberIndex),
64 MemberRelativeOffset(std::move(MemberRelativeOffset)) {}
65 };
67 for (User *U : GV.users()) {
68 auto *GEP = dyn_cast<GEPOperator>(U);
69 if (!GEP)
70 return false;
71
72 std::optional<ConstantRange> InRange = GEP->getInRange();
73 if (!InRange)
74 return false;
75
76 APInt Offset(IndexWidth, 0);
77 if (!GEP->accumulateConstantOffset(DL, Offset))
78 return false;
79
80 // Determine source-relative inrange.
81 ConstantRange SrcInRange = InRange->sextOrTrunc(IndexWidth).add(Offset);
82
83 // Check that the GEP offset is in the range (treating upper bound as
84 // inclusive here).
85 if (!SrcInRange.contains(Offset) && SrcInRange.getUpper() != Offset)
86 return false;
87
88 // Find which struct member the range corresponds to.
89 if (SrcInRange.getLower().uge(SL->getSizeInBytes()))
90 return false;
91
92 unsigned MemberIndex =
94 TypeSize MemberStart = MemberOffsets[MemberIndex];
95 TypeSize MemberEnd = MemberIndex == MemberOffsets.size() - 1
96 ? SL->getSizeInBytes()
97 : MemberOffsets[MemberIndex + 1];
98
99 // Verify that the range matches that struct member.
100 if (SrcInRange.getLower() != MemberStart ||
101 SrcInRange.getUpper() != MemberEnd)
102 return false;
103
104 Infos.emplace_back(GEP, MemberIndex, Offset - MemberStart);
105 }
106
108 GV.getMetadata(LLVMContext::MD_type, Types);
109
111
112 std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
113 for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
114 // Build a global representing this split piece.
115 auto *SplitGV =
116 new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
118 Init->getOperand(I), GV.getName() + "." + utostr(I));
119 SplitGlobals[I] = SplitGV;
120
121 unsigned SplitBegin = SL->getElementOffset(I);
122 unsigned SplitEnd = (I == Init->getNumOperands() - 1)
123 ? SL->getSizeInBytes()
124 : SL->getElementOffset(I + 1);
125
126 // Rebuild type metadata, adjusting by the split offset.
127 // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
128 for (MDNode *Type : Types) {
129 uint64_t ByteOffset = cast<ConstantInt>(
130 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
131 ->getZExtValue();
132 // Type metadata may be attached one byte after the end of the vtable, for
133 // classes without virtual methods in Itanium ABI. AFAIK, it is never
134 // attached to the first byte of a vtable. Subtract one to get the right
135 // slice.
136 // This is making an assumption that vtable groups are the only kinds of
137 // global variables that !type metadata can be attached to, and that they
138 // are either Itanium ABI vtable groups or contain a single vtable (i.e.
139 // Microsoft ABI vtables).
140 uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
141 if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
142 continue;
143 SplitGV->addMetadata(
144 LLVMContext::MD_type,
146 {ConstantAsMetadata::get(
147 ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
148 Type->getOperand(1)}));
149 }
150
151 if (GV.hasMetadata(LLVMContext::MD_vcall_visibility))
152 SplitGV->setVCallVisibilityMetadata(GV.getVCallVisibility());
153 }
154
155 for (const GEPInfo &Info : Infos) {
156 assert(Info.MemberIndex < SplitGlobals.size() && "Invalid member");
157 auto *NewGEP = ConstantExpr::getGetElementPtr(
158 Type::getInt8Ty(GV.getContext()), SplitGlobals[Info.MemberIndex],
159 ConstantInt::get(GV.getContext(), Info.MemberRelativeOffset),
160 Info.GEP->isInBounds());
161 Info.GEP->replaceAllUsesWith(NewGEP);
162 }
163
164 // Finally, remove the original global. Any remaining uses refer to invalid
165 // elements of the global, so replace with poison.
166 if (!GV.use_empty())
168 GV.eraseFromParent();
169 return true;
170}
171
172static bool splitGlobals(Module &M) {
173 // First, see if the module uses either of the llvm.type.test or
174 // llvm.type.checked.load intrinsics, which indicates that splitting globals
175 // may be beneficial.
176 Function *TypeTestFunc =
177 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
178 Function *TypeCheckedLoadFunc =
179 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
180 Function *TypeCheckedLoadRelativeFunc =
181 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load_relative));
182 if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
183 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()) &&
184 (!TypeCheckedLoadRelativeFunc ||
185 TypeCheckedLoadRelativeFunc->use_empty()))
186 return false;
187
188 bool Changed = false;
189 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals()))
190 Changed |= splitGlobal(GV);
191 return Changed;
192}
193
195 if (!splitGlobals(M))
196 return PreservedAnalyses::all();
198}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool splitGlobals(Module &M)
static bool splitGlobal(GlobalVariable &GV)
Definition: GlobalSplit.cpp:39
Hexagon Common GEP
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
Class for arbitrary precision integers.
Definition: APInt.h:76
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1199
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1200
This class represents a range of values.
Definition: ConstantRange.h:47
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:589
VCallVisibility getVCallVisibility() const
Definition: Metadata.cpp:1816
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:462
Class to represent integer types.
Definition: DerivedTypes.h:40
Metadata node.
Definition: Metadata.h:1067
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:293
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:622
TypeSize getSizeInBytes() const
Definition: DataLayout.h:629
MutableArrayRef< TypeSize > getMemberOffsets()
Definition: DataLayout.h:643
unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
Definition: DataLayout.cpp:92
TypeSize getElementOffset(unsigned Idx) const
Definition: DataLayout.h:651
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:1023
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656