LLVM 24.0.0git
GlobalOpt.cpp
Go to the documentation of this file.
1//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 transforms simple global variables that never have their address
10// taken. If obviously true, it marks read/write globals as constant, deletes
11// variables only stored to, etc.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/Twine.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalAlias.h"
41#include "llvm/IR/GlobalValue.h"
43#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/Operator.h"
51#include "llvm/IR/Type.h"
52#include "llvm/IR/Use.h"
53#include "llvm/IR/User.h"
54#include "llvm/IR/Value.h"
55#include "llvm/IR/ValueHandle.h"
59#include "llvm/Support/Debug.h"
62#include "llvm/Transforms/IPO.h"
67#include <cassert>
68#include <cstdint>
69#include <optional>
70#include <utility>
71#include <vector>
72
73using namespace llvm;
74
75#define DEBUG_TYPE "globalopt"
76
77STATISTIC(NumMarked , "Number of globals marked constant");
78STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
79STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
80STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
81STATISTIC(NumDeleted , "Number of globals deleted");
82STATISTIC(NumGlobUses , "Number of global uses devirtualized");
83STATISTIC(NumLocalized , "Number of globals localized");
84STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
85STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
86STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
87STATISTIC(NumNestRemoved , "Number of nest attributes removed");
88STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
89STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
90STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
91STATISTIC(NumAtExitRemoved, "Number of atexit handlers removed");
92STATISTIC(NumInternalFunc, "Number of internal functions");
93STATISTIC(NumColdCC, "Number of functions marked coldcc");
94STATISTIC(NumIFuncsResolved, "Number of statically resolved IFuncs");
95STATISTIC(NumIFuncsDeleted, "Number of IFuncs removed");
96
97static cl::opt<bool>
98 OptimizeNonFMVCallers("optimize-non-fmv-callers",
99 cl::desc("Statically resolve calls to versioned "
100 "functions from non-versioned callers."),
101 cl::init(true), cl::Hidden);
102
104 "max-ifunc-versions", cl::Hidden, cl::init(5),
105 cl::desc("Maximum number of caller/callee versions that is allowed for "
106 "using the expensive (cubic) static resolution algorithm."));
107
108static cl::opt<bool>
109 EnableColdCCStressTest("enable-coldcc-stress-test",
110 cl::desc("Enable stress test of coldcc by adding "
111 "calling conv to all internal functions."),
112 cl::init(false), cl::Hidden);
113
115 "coldcc-rel-freq", cl::Hidden, cl::init(2),
116 cl::desc(
117 "Maximum block frequency, expressed as a percentage of caller's "
118 "entry frequency, for a call site to be considered cold for enabling "
119 "coldcc"));
120
121/// Is this global variable possibly used by a leak checker as a root? If so,
122/// we might not really want to eliminate the stores to it.
124 // A global variable is a root if it is a pointer, or could plausibly contain
125 // a pointer. There are two challenges; one is that we could have a struct
126 // the has an inner member which is a pointer. We recurse through the type to
127 // detect these (up to a point). The other is that we may actually be a union
128 // of a pointer and another type, and so our LLVM type is an integer which
129 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
130 // potentially contained here.
131
132 if (GV->hasPrivateLinkage())
133 return false;
134
136 Types.push_back(GV->getValueType());
137
138 unsigned Limit = 20;
139 do {
140 Type *Ty = Types.pop_back_val();
141 switch (Ty->getTypeID()) {
142 default: break;
144 return true;
147 if (cast<VectorType>(Ty)->getElementType()->isPointerTy())
148 return true;
149 break;
150 case Type::ArrayTyID:
151 Types.push_back(cast<ArrayType>(Ty)->getElementType());
152 break;
153 case Type::StructTyID: {
154 StructType *STy = cast<StructType>(Ty);
155 if (STy->isOpaque()) return true;
156 for (Type *InnerTy : STy->elements()) {
157 if (isa<PointerType>(InnerTy)) return true;
158 if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) ||
159 isa<VectorType>(InnerTy))
160 Types.push_back(InnerTy);
161 }
162 break;
163 }
164 }
165 if (--Limit == 0) return true;
166 } while (!Types.empty());
167 return false;
168}
169
170/// Given a value that is stored to a global but never read, determine whether
171/// it's safe to remove the store and the chain of computation that feeds the
172/// store.
174 Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
175 do {
176 if (isa<Constant>(V))
177 return true;
178 if (!V->hasOneUse())
179 return false;
180 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
182 return false;
183 if (isAllocationFn(V, GetTLI))
184 return true;
185
187 if (I->mayHaveSideEffects())
188 return false;
190 if (!GEP->hasAllConstantIndices())
191 return false;
192 } else if (I->getNumOperands() != 1) {
193 return false;
194 }
195
196 V = I->getOperand(0);
197 } while (true);
198}
199
200/// This GV is a pointer root. Loop over all users of the global and clean up
201/// any that obviously don't assign the global a value that isn't dynamically
202/// allocated.
203static bool
206 // A brief explanation of leak checkers. The goal is to find bugs where
207 // pointers are forgotten, causing an accumulating growth in memory
208 // usage over time. The common strategy for leak checkers is to explicitly
209 // allow the memory pointed to by globals at exit. This is popular because it
210 // also solves another problem where the main thread of a C++ program may shut
211 // down before other threads that are still expecting to use those globals. To
212 // handle that case, we expect the program may create a singleton and never
213 // destroy it.
214
215 bool Changed = false;
216
217 // If Dead[n].first is the only use of a malloc result, we can delete its
218 // chain of computation and the store to the global in Dead[n].second.
220
221 SmallVector<User *> Worklist(GV->users());
222 // Constants can't be pointers to dynamically allocated memory.
223 while (!Worklist.empty()) {
224 User *U = Worklist.pop_back_val();
225 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
226 Value *V = SI->getValueOperand();
227 if (isa<Constant>(V)) {
228 Changed = true;
229 SI->eraseFromParent();
230 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
231 if (I->hasOneUse())
232 Dead.push_back(std::make_pair(I, SI));
233 }
234 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
235 if (isa<Constant>(MSI->getValue())) {
236 Changed = true;
237 MSI->eraseFromParent();
238 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
239 if (I->hasOneUse())
240 Dead.push_back(std::make_pair(I, MSI));
241 }
242 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
243 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
244 if (MemSrc && MemSrc->isConstant()) {
245 Changed = true;
246 MTI->eraseFromParent();
247 } else if (Instruction *I = dyn_cast<Instruction>(MTI->getSource())) {
248 if (I->hasOneUse())
249 Dead.push_back(std::make_pair(I, MTI));
250 }
251 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
252 if (isa<GEPOperator>(CE))
253 append_range(Worklist, CE->users());
254 }
255 }
256
257 for (const auto &[Inst, Store] : Dead) {
258 if (IsSafeComputationToRemove(Inst, GetTLI)) {
259 Store->eraseFromParent();
260 Instruction *I = Inst;
261 do {
262 if (isAllocationFn(I, GetTLI))
263 break;
264 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
265 if (!J)
266 break;
267 I->eraseFromParent();
268 I = J;
269 } while (true);
270 I->eraseFromParent();
271 Changed = true;
272 }
273 }
274
276 return Changed;
277}
278
279/// We just marked GV constant. Loop over all users of the global, cleaning up
280/// the obvious ones. This is largely just a quick scan over the use list to
281/// clean up the easy and obvious cruft. This returns true if it made a change.
283 const DataLayout &DL) {
285 SmallVector<User *, 8> WorkList(GV->users());
287 bool Changed = false;
288
289 SmallVector<WeakTrackingVH> MaybeDeadInsts;
290 auto EraseFromParent = [&](Instruction *I) {
291 for (Value *Op : I->operands())
292 if (auto *OpI = dyn_cast<Instruction>(Op))
293 MaybeDeadInsts.push_back(OpI);
294 I->eraseFromParent();
295 Changed = true;
296 };
297 while (!WorkList.empty()) {
298 User *U = WorkList.pop_back_val();
299 if (!Visited.insert(U).second)
300 continue;
301
302 if (auto *BO = dyn_cast<BitCastOperator>(U))
303 append_range(WorkList, BO->users());
304 if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U))
305 append_range(WorkList, ASC->users());
306 else if (auto *GEP = dyn_cast<GEPOperator>(U))
307 append_range(WorkList, GEP->users());
308 else if (auto *LI = dyn_cast<LoadInst>(U)) {
309 // A load from a uniform value is always the same, regardless of any
310 // applied offset.
311 Type *Ty = LI->getType();
313 LI->replaceAllUsesWith(Res);
314 EraseFromParent(LI);
315 continue;
316 }
317
318 Value *PtrOp = LI->getPointerOperand();
319 APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
321 DL, Offset, /* AllowNonInbounds */ true);
323 if (II->getIntrinsicID() == Intrinsic::threadlocal_address)
324 PtrOp = II->getArgOperand(0);
325 }
326 if (PtrOp == GV) {
327 if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) {
328 LI->replaceAllUsesWith(Value);
329 EraseFromParent(LI);
330 }
331 }
332 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
333 // Store must be unreachable or storing Init into the global.
334 EraseFromParent(SI);
335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (getUnderlyingObject(MI->getRawDest()) == GV)
337 EraseFromParent(MI);
338 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
339 if (II->getIntrinsicID() == Intrinsic::threadlocal_address)
340 append_range(WorkList, II->users());
341 }
342 }
343
344 Changed |=
347 return Changed;
348}
349
350/// Part of the global at a specific offset, which is only accessed through
351/// loads and stores with the given type.
355 bool IsLoaded = false;
356 bool IsStored = false;
357};
358
359/// Look at all uses of the global and determine which (offset, type) pairs it
360/// can be split into.
362 GlobalVariable *GV, const DataLayout &DL) {
363 SmallVector<Use *, 16> Worklist;
365 auto AppendUses = [&](Value *V) {
366 for (Use &U : V->uses())
367 if (Visited.insert(&U).second)
368 Worklist.push_back(&U);
369 };
370 AppendUses(GV);
371 while (!Worklist.empty()) {
372 Use *U = Worklist.pop_back_val();
373 User *V = U->getUser();
374
375 auto *GEP = dyn_cast<GEPOperator>(V);
377 (GEP && GEP->hasAllConstantIndices())) {
378 AppendUses(V);
379 continue;
380 }
381
382 if (Value *Ptr = getLoadStorePointerOperand(V)) {
383 // This is storing the global address into somewhere, not storing into
384 // the global.
385 if (isa<StoreInst>(V) && U->getOperandNo() == 0)
386 return false;
387
388 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
389 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
390 /* AllowNonInbounds */ true);
391 if (Ptr != GV || Offset.getActiveBits() >= 64)
392 return false;
393
394 // TODO: We currently require that all accesses at a given offset must
395 // use the same type. This could be relaxed.
396 Type *Ty = getLoadStoreType(V);
397 const auto &[It, Inserted] =
398 Parts.try_emplace(Offset.getZExtValue(), GlobalPart{Ty});
399 if (Ty != It->second.Ty)
400 return false;
401
402 if (Inserted) {
403 It->second.Initializer =
405 if (!It->second.Initializer) {
406 LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of "
407 << *GV << " with type " << *Ty << " at offset "
408 << Offset.getZExtValue());
409 return false;
410 }
411 }
412
413 // Scalable types not currently supported.
414 if (Ty->isScalableTy())
415 return false;
416
417 auto IsStored = [](Value *V, Constant *Initializer) {
418 auto *SI = dyn_cast<StoreInst>(V);
419 if (!SI)
420 return false;
421
422 Constant *StoredConst = dyn_cast<Constant>(SI->getOperand(0));
423 if (!StoredConst)
424 return true;
425
426 // Don't consider stores that only write the initializer value.
427 return Initializer != StoredConst;
428 };
429
430 It->second.IsLoaded |= isa<LoadInst>(V);
431 It->second.IsStored |= IsStored(V, It->second.Initializer);
432 continue;
433 }
434
435 // Ignore dead constant users.
436 if (auto *C = dyn_cast<Constant>(V)) {
438 return false;
439 continue;
440 }
441
442 // Unknown user.
443 return false;
444 }
445
446 return true;
447}
448
449/// Copy over the debug info for a variable to its SRA replacements.
451 uint64_t FragmentOffsetInBits,
452 uint64_t FragmentSizeInBits,
453 uint64_t VarSize) {
455 GV->getDebugInfo(GVs);
456 for (auto *GVE : GVs) {
457 DIVariable *Var = GVE->getVariable();
458 DIExpression *Expr = GVE->getExpression();
459 int64_t CurVarOffsetInBytes = 0;
460 uint64_t CurVarOffsetInBits = 0;
461 uint64_t FragmentEndInBits = FragmentOffsetInBits + FragmentSizeInBits;
462
463 // Calculate the offset (Bytes), Continue if unknown.
464 if (!Expr->extractIfOffset(CurVarOffsetInBytes))
465 continue;
466
467 // Ignore negative offset.
468 if (CurVarOffsetInBytes < 0)
469 continue;
470
471 // Convert offset to bits.
472 CurVarOffsetInBits = CHAR_BIT * (uint64_t)CurVarOffsetInBytes;
473
474 // Current var starts after the fragment, ignore.
475 if (CurVarOffsetInBits >= FragmentEndInBits)
476 continue;
477
478 uint64_t CurVarSize = Var->getType()->getSizeInBits();
479 uint64_t CurVarEndInBits = CurVarOffsetInBits + CurVarSize;
480 // Current variable ends before start of fragment, ignore.
481 if (CurVarSize != 0 && /* CurVarSize is known */
482 CurVarEndInBits <= FragmentOffsetInBits)
483 continue;
484
485 // Current variable fits in (not greater than) the fragment,
486 // does not need fragment expression.
487 if (CurVarSize != 0 && /* CurVarSize is known */
488 CurVarOffsetInBits >= FragmentOffsetInBits &&
489 CurVarEndInBits <= FragmentEndInBits) {
490 uint64_t CurVarOffsetInFragment =
491 (CurVarOffsetInBits - FragmentOffsetInBits) / 8;
492 if (CurVarOffsetInFragment != 0)
493 Expr = DIExpression::get(Expr->getContext(), {dwarf::DW_OP_plus_uconst,
494 CurVarOffsetInFragment});
495 else
496 Expr = DIExpression::get(Expr->getContext(), {});
497 auto *NGVE =
498 DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
499 NGV->addDebugInfo(NGVE);
500 continue;
501 }
502 // Current variable does not fit in single fragment,
503 // emit a fragment expression.
504 if (FragmentSizeInBits < VarSize) {
505 if (CurVarOffsetInBits > FragmentOffsetInBits)
506 continue;
507 uint64_t CurVarFragmentOffsetInBits =
508 FragmentOffsetInBits - CurVarOffsetInBits;
509 uint64_t CurVarFragmentSizeInBits = FragmentSizeInBits;
510 if (CurVarSize != 0 && CurVarEndInBits < FragmentEndInBits)
511 CurVarFragmentSizeInBits -= (FragmentEndInBits - CurVarEndInBits);
512 if (CurVarOffsetInBits)
513 Expr = DIExpression::get(Expr->getContext(), {});
515 Expr, CurVarFragmentOffsetInBits, CurVarFragmentSizeInBits))
516 Expr = *E;
517 else
518 continue;
519 }
520 auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
521 NGV->addDebugInfo(NGVE);
522 }
523}
524
525/// Perform scalar replacement of aggregates on the specified global variable.
526/// This opens the door for other optimizations by exposing the behavior of the
527/// program in a more fine-grained way. We have determined that this
528/// transformation is safe already. We return the first global variable we
529/// insert so that the caller can reprocess it.
531 assert(GV->hasLocalLinkage());
532
533 // Collect types to split into.
535 if (!collectSRATypes(Parts, GV, DL) || Parts.empty())
536 return nullptr;
537
538 // Make sure we don't SRA back to the same type.
539 if (Parts.size() == 1 && Parts.begin()->second.Ty == GV->getValueType())
540 return nullptr;
541
542 // Don't perform SRA if we would have to split into many globals. Ignore
543 // parts that are either only loaded or only stored, because we expect them
544 // to be optimized away.
545 unsigned NumParts = count_if(Parts, [](const auto &Pair) {
546 return Pair.second.IsLoaded && Pair.second.IsStored;
547 });
548 if (NumParts > 16)
549 return nullptr;
550
551 // Sort by offset.
553 for (const auto &Pair : Parts) {
554 TypesVector.push_back(
555 {Pair.first, Pair.second.Ty, Pair.second.Initializer});
556 }
557 sort(TypesVector, llvm::less_first());
558
559 // Check that the types are non-overlapping.
560 uint64_t Offset = 0;
561 for (const auto &[OffsetForTy, Ty, _] : TypesVector) {
562 // Overlaps with previous type.
563 if (OffsetForTy < Offset)
564 return nullptr;
565
566 Offset = OffsetForTy + DL.getTypeAllocSize(Ty);
567 }
568
569 // Some accesses go beyond the end of the global, don't bother.
570 if (Offset > GV->getGlobalSize(DL))
571 return nullptr;
572
573 LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
574
575 // Get the alignment of the global, either explicit or target-specific.
576 Align StartAlignment =
577 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
578 uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType());
579
580 // Create replacement globals.
582 unsigned NameSuffix = 0;
583 for (auto &[OffsetForTy, Ty, Initializer] : TypesVector) {
586 Initializer, GV->getName() + "." + Twine(NameSuffix++), GV,
588 // Start out by copying attributes from the original, including alignment.
589 NGV->copyAttributesFrom(GV);
590 NewGlobals.insert({OffsetForTy, NGV});
591
592 // Calculate the known alignment of the field. If the original aggregate
593 // had 256 byte alignment for example, then the element at a given offset
594 // may also have a known alignment, and something might depend on that:
595 // propagate info to each field.
596 Align NewAlign = commonAlignment(StartAlignment, OffsetForTy);
597 NGV->setAlignment(NewAlign);
598
599 // Copy over the debug info for the variable.
600 transferSRADebugInfo(GV, NGV, OffsetForTy * 8,
601 DL.getTypeAllocSizeInBits(Ty), VarSize);
602 }
603
604 // Replace uses of the original global with uses of the new global.
608 auto AppendUsers = [&](Value *V) {
609 for (User *U : V->users())
610 if (Visited.insert(U).second)
611 Worklist.push_back(U);
612 };
613 AppendUsers(GV);
614 while (!Worklist.empty()) {
615 Value *V = Worklist.pop_back_val();
617 isa<GEPOperator>(V)) {
618 AppendUsers(V);
619 if (isa<Instruction>(V))
620 DeadInsts.push_back(V);
621 continue;
622 }
623
624 if (Value *Ptr = getLoadStorePointerOperand(V)) {
625 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
626 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
627 /* AllowNonInbounds */ true);
628 assert(Ptr == GV && "Load/store must be from/to global");
629 GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()];
630 assert(NGV && "Must have replacement global for this offset");
631
632 // Update the pointer operand and recalculate alignment.
633 Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V));
634 Align NewAlign =
636
637 if (auto *LI = dyn_cast<LoadInst>(V)) {
638 LI->setOperand(0, NGV);
639 LI->setAlignment(NewAlign);
640 } else {
641 auto *SI = cast<StoreInst>(V);
642 SI->setOperand(1, NGV);
643 SI->setAlignment(NewAlign);
644 }
645 continue;
646 }
647
649 "Other users can only be dead constants");
650 }
651
652 // Delete old instructions and global.
655 GV->eraseFromParent();
656 ++NumSRA;
657
658 assert(NewGlobals.size() > 0);
659 return NewGlobals.begin()->second;
660}
661
662/// Return true if all users of the specified value will trap if the value is
663/// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
664/// reprocessing them.
667 for (const User *U : V->users()) {
668 if (const Instruction *I = dyn_cast<Instruction>(U)) {
669 // If null pointer is considered valid, then all uses are non-trapping.
670 // Non address-space 0 globals have already been pruned by the caller.
671 if (NullPointerIsDefined(I->getFunction()))
672 return false;
673 }
674 if (isa<LoadInst>(U)) {
675 // Will trap.
676 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
677 if (SI->getOperand(0) == V) {
678 return false; // Storing the value.
679 }
680 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
681 if (CI->getCalledOperand() != V) {
682 return false; // Not calling the ptr
683 }
684 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
685 if (II->getCalledOperand() != V) {
686 return false; // Not calling the ptr
687 }
688 } else if (const AddrSpaceCastInst *CI = dyn_cast<AddrSpaceCastInst>(U)) {
689 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs))
690 return false;
691 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
692 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
693 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
694 // If we've already seen this phi node, ignore it, it has already been
695 // checked.
696 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
697 return false;
698 } else if (isa<ICmpInst>(U) &&
699 !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) &&
700 isa<LoadInst>(U->getOperand(0)) &&
701 isa<ConstantPointerNull>(U->getOperand(1))) {
702 assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0))
703 ->getPointerOperand()
704 ->stripPointerCasts()) &&
705 "Should be GlobalVariable");
706 // This and only this kind of non-signed ICmpInst is to be replaced with
707 // the comparing of the value of the created global init bool later in
708 // optimizeGlobalAddressOfAllocation for the global variable.
709 } else {
710 return false;
711 }
712 }
713 return true;
714}
715
716/// Return true if all uses of any loads from GV will trap if the loaded value
717/// is null. Note that this also permits comparisons of the loaded value
718/// against null, as a special case.
721 Worklist.push_back(GV);
722 while (!Worklist.empty()) {
723 const Value *P = Worklist.pop_back_val();
724 for (const auto *U : P->users()) {
725 if (auto *LI = dyn_cast<LoadInst>(U)) {
726 if (!LI->isSimple())
727 return false;
729 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
730 return false;
731 } else if (auto *SI = dyn_cast<StoreInst>(U)) {
732 if (!SI->isSimple())
733 return false;
734 // Ignore stores to the global.
735 if (SI->getPointerOperand() != P)
736 return false;
737 } else if (auto *CE = dyn_cast<ConstantExpr>(U)) {
738 if (CE->stripPointerCasts() != GV)
739 return false;
740 // Check further the ConstantExpr.
741 Worklist.push_back(CE);
742 } else {
743 // We don't know or understand this user, bail out.
744 return false;
745 }
746 }
747 }
748
749 return true;
750}
751
752/// Get all the loads/store uses for global variable \p GV.
756 Worklist.push_back(GV);
757 while (!Worklist.empty()) {
758 auto *P = Worklist.pop_back_val();
759 for (auto *U : P->users()) {
760 if (auto *CE = dyn_cast<ConstantExpr>(U)) {
761 Worklist.push_back(CE);
762 continue;
763 }
764
766 "Expect only load or store instructions");
767 Uses.push_back(U);
768 }
769 }
770}
771
773 bool Changed = false;
774 SmallVector<User *, 8> Users(V->user_begin(), V->user_end());
775 for (User *U : Users) {
777 // Uses are non-trapping if null pointer is considered valid.
778 // Non address-space 0 globals are already pruned by the caller.
779 if (NullPointerIsDefined(I->getFunction()))
780 return false;
781 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
782 LI->setOperand(0, NewV);
783 Changed = true;
784 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
785 if (SI->getOperand(1) == V) {
786 SI->setOperand(1, NewV);
787 Changed = true;
788 }
789 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
791 if (CB->getCalledOperand() == V) {
792 // Calling through the pointer! Turn into a direct call, but be careful
793 // that the pointer is not also being passed as an argument.
794 CB->setCalledOperand(NewV);
795 Changed = true;
796 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
797 if (CB->getArgOperand(i) == V)
798 CB->setArgOperand(i, NewV);
799 }
802 CI, ConstantExpr::getAddrSpaceCast(NewV, CI->getType()));
803 if (CI->use_empty()) {
804 Changed = true;
805 CI->eraseFromParent();
806 }
807 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
808 // Should handle GEP here.
810 Idxs.reserve(GEPI->getNumOperands()-1);
811 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
812 i != e; ++i)
813 if (Constant *C = dyn_cast<Constant>(*i))
814 Idxs.push_back(C);
815 else
816 break;
817 if (Idxs.size() == GEPI->getNumOperands()-1)
819 GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(),
820 NewV, Idxs));
821 if (GEPI->use_empty()) {
822 Changed = true;
823 GEPI->eraseFromParent();
824 }
825 }
826 }
827
828 return Changed;
829}
830
831/// The specified global has only one non-null value stored into it. If there
832/// are uses of the loaded value that would trap if the loaded value is
833/// dynamically null, then we know that they cannot be reachable with a null
834/// optimize away the load.
836 GlobalVariable *GV, Constant *LV, const DataLayout &DL,
838 bool Changed = false;
839
840 // Keep track of whether we are able to remove all the uses of the global
841 // other than the store that defines it.
842 bool AllNonStoreUsesGone = true;
843
844 // Replace all uses of loads with uses of uses of the stored value.
845 for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) {
846 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
848 // If we were able to delete all uses of the loads
849 if (LI->use_empty()) {
850 LI->eraseFromParent();
851 Changed = true;
852 } else {
853 AllNonStoreUsesGone = false;
854 }
855 } else if (isa<StoreInst>(GlobalUser)) {
856 // Ignore the store that stores "LV" to the global.
857 assert(GlobalUser->getOperand(1) == GV &&
858 "Must be storing *to* the global");
859 } else {
860 AllNonStoreUsesGone = false;
861
862 // If we get here we could have other crazy uses that are transitively
863 // loaded.
864 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
865 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
866 isa<BitCastInst>(GlobalUser) ||
867 isa<GetElementPtrInst>(GlobalUser) ||
868 isa<AddrSpaceCastInst>(GlobalUser)) &&
869 "Only expect load and stores!");
870 }
871 }
872
873 if (Changed) {
874 LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
875 << "\n");
876 ++NumGlobUses;
877 }
878
879 // If we nuked all of the loads, then none of the stores are needed either,
880 // nor is the global.
881 if (AllNonStoreUsesGone) {
882 if (isLeakCheckerRoot(GV)) {
883 Changed |= CleanupPointerRootUsers(GV, GetTLI);
884 } else {
885 Changed = true;
887 }
888 if (GV->use_empty()) {
889 LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
890 Changed = true;
891 GV->eraseFromParent();
892 ++NumDeleted;
893 }
894 }
895 return Changed;
896}
897
898/// Walk the use list of V, constant folding all of the instructions that are
899/// foldable.
900static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
901 TargetLibraryInfo *TLI) {
902 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
903 if (Instruction *I = dyn_cast<Instruction>(*UI++))
904 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
905 I->replaceAllUsesWith(NewC);
906
907 // Advance UI to the next non-I use to avoid invalidating it!
908 // Instructions could multiply use V.
909 while (UI != E && *UI == I)
910 ++UI;
912 I->eraseFromParent();
913 }
914}
915
916/// This function takes the specified global variable, and transforms the
917/// program as if it always contained the result of the specified malloc.
918/// Because it is always the result of the specified malloc, there is no reason
919/// to actually DO the malloc. Instead, turn the malloc into a global, and any
920/// loads of GV as uses of the new global.
921static GlobalVariable *
923 uint64_t AllocSize, Constant *InitVal,
924 const DataLayout &DL,
925 TargetLibraryInfo *TLI) {
926 LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI
927 << '\n');
928
929 // Create global of type [AllocSize x i8].
930 Type *GlobalType = ArrayType::get(Type::getInt8Ty(GV->getContext()),
931 AllocSize);
932
933 // Create the new global variable. The contents of the allocated memory is
934 // undefined initially, so initialize with an undef value.
935 GlobalVariable *NewGV = new GlobalVariable(
936 *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage,
937 UndefValue::get(GlobalType), GV->getName() + ".body", nullptr,
938 GV->getThreadLocalMode());
939
940 // Initialize the global at the point of the original call. Note that this
941 // is a different point from the initialization referred to below for the
942 // nullability handling. Sublety: We have not proven the original global was
943 // only initialized once. As such, we can not fold this into the initializer
944 // of the new global as may need to re-init the storage multiple times.
945 if (!isa<UndefValue>(InitVal)) {
946 IRBuilder<> Builder(CI->getNextNode());
947 // TODO: Use alignment above if align!=1
948 Builder.CreateMemSet(NewGV, InitVal, AllocSize, std::nullopt);
949 }
950
951 // Update users of the allocation to use the new global instead.
952 CI->replaceAllUsesWith(NewGV);
953
954 // If there is a comparison against null, we will insert a global bool to
955 // keep track of whether the global was initialized yet or not.
956 GlobalVariable *InitBool = new GlobalVariable(
958 ConstantInt::getFalse(GV->getContext()), GV->getName() + ".init",
960 bool InitBoolUsed = false;
961
962 // Loop over all instruction uses of GV, processing them in turn.
964 allUsesOfLoadAndStores(GV, Guses);
965 for (auto *U : Guses) {
966 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
967 // The global is initialized when the store to it occurs. If the stored
968 // value is null value, the global bool is set to false, otherwise true.
969 auto *NewSI = new StoreInst(
971 SI->getValueOperand())),
972 InitBool, false, Align(1), SI->getOrdering(), SI->getSyncScopeID(),
973 SI->getIterator());
974 NewSI->setDebugLoc(SI->getDebugLoc());
975 SI->eraseFromParent();
976 continue;
977 }
978
979 LoadInst *LI = cast<LoadInst>(U);
980 while (!LI->use_empty()) {
981 Use &LoadUse = *LI->use_begin();
982 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
983 if (!ICI) {
984 LoadUse.set(NewGV);
985 continue;
986 }
987
988 // Replace the cmp X, 0 with a use of the bool value.
989 Value *LV = new LoadInst(InitBool->getValueType(), InitBool,
990 InitBool->getName() + ".val", false, Align(1),
991 LI->getOrdering(), LI->getSyncScopeID(),
992 LI->getIterator());
993 // FIXME: Should we use the DebugLoc of the load used by the predicate, or
994 // the predicate? The load seems most appropriate, but there's an argument
995 // that the new load does not represent the old load, but is simply a
996 // component of recomputing the predicate.
997 cast<LoadInst>(LV)->setDebugLoc(LI->getDebugLoc());
998 InitBoolUsed = true;
999 switch (ICI->getPredicate()) {
1000 default: llvm_unreachable("Unknown ICmp Predicate!");
1001 case ICmpInst::ICMP_ULT: // X < null -> always false
1003 break;
1004 case ICmpInst::ICMP_UGE: // X >= null -> always true
1005 LV = ConstantInt::getTrue(GV->getContext());
1006 break;
1007 case ICmpInst::ICMP_ULE:
1008 case ICmpInst::ICMP_EQ:
1009 LV = BinaryOperator::CreateNot(LV, "notinit", ICI->getIterator());
1010 cast<BinaryOperator>(LV)->setDebugLoc(ICI->getDebugLoc());
1011 break;
1012 case ICmpInst::ICMP_NE:
1013 case ICmpInst::ICMP_UGT:
1014 break; // no change.
1015 }
1016 ICI->replaceAllUsesWith(LV);
1017 ICI->eraseFromParent();
1018 }
1019 LI->eraseFromParent();
1020 }
1021
1022 // If the initialization boolean was used, insert it, otherwise delete it.
1023 if (!InitBoolUsed) {
1024 while (!InitBool->use_empty()) // Delete initializations
1025 cast<StoreInst>(InitBool->user_back())->eraseFromParent();
1026 delete InitBool;
1027 } else
1028 GV->getParent()->insertGlobalVariable(GV->getIterator(), InitBool);
1029
1030 // Now the GV is dead, nuke it and the allocation..
1031 GV->eraseFromParent();
1032 CI->eraseFromParent();
1033
1034 // To further other optimizations, loop over all users of NewGV and try to
1035 // constant prop them. This will promote GEP instructions with constant
1036 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
1037 ConstantPropUsersOf(NewGV, DL, TLI);
1038
1039 return NewGV;
1040}
1041
1042/// Scan the use-list of GV checking to make sure that there are no complex uses
1043/// of GV. We permit simple things like dereferencing the pointer, but not
1044/// storing through the address, unless it is to the specified global.
1045static bool
1047 const GlobalVariable *GV) {
1050 Worklist.push_back(CI);
1051
1052 while (!Worklist.empty()) {
1053 const Value *V = Worklist.pop_back_val();
1054 if (!Visited.insert(V).second)
1055 continue;
1056
1057 for (const Use &VUse : V->uses()) {
1058 const User *U = VUse.getUser();
1059 if (isa<LoadInst>(U) || isa<CmpInst>(U))
1060 continue; // Fine, ignore.
1061
1062 if (auto *SI = dyn_cast<StoreInst>(U)) {
1063 if (SI->getValueOperand() == V &&
1064 SI->getPointerOperand()->stripPointerCasts() != GV)
1065 return false; // Storing the pointer not into GV... bad.
1066 continue; // Otherwise, storing through it, or storing into GV... fine.
1067 }
1068
1069 if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1070 Worklist.push_back(GEPI);
1071 continue;
1072 }
1073
1074 return false;
1075 }
1076 }
1077
1078 return true;
1079}
1080
1081/// If we have a global that is only initialized with a fixed size allocation
1082/// try to transform the program to use global memory instead of heap
1083/// allocated memory. This eliminates dynamic allocation, avoids an indirection
1084/// accessing the data, and exposes the resultant global to further GlobalOpt.
1086 CallInst *CI,
1087 const DataLayout &DL,
1088 TargetLibraryInfo *TLI) {
1089 if (!isRemovableAlloc(CI, TLI))
1090 // Must be able to remove the call when we get done..
1091 return false;
1092
1093 Type *Int8Ty = Type::getInt8Ty(CI->getFunction()->getContext());
1094 Constant *InitVal = getInitialValueOfAllocation(CI, TLI, Int8Ty);
1095 if (!InitVal)
1096 // Must be able to emit a memset for initialization
1097 return false;
1098
1099 uint64_t AllocSize;
1100 if (!getObjectSize(CI, AllocSize, DL, TLI, ObjectSizeOpts()))
1101 return false;
1102
1103 // Restrict this transformation to only working on small allocations
1104 // (2048 bytes currently), as we don't want to introduce a 16M global or
1105 // something.
1106 if (AllocSize >= 2048)
1107 return false;
1108
1109 // We can't optimize this global unless all uses of it are *known* to be
1110 // of the malloc value, not of the null initializer value (consider a use
1111 // that compares the global's value against zero to see if the malloc has
1112 // been reached). To do this, we check to see if all uses of the global
1113 // would trap if the global were null: this proves that they must all
1114 // happen after the malloc.
1116 return false;
1117
1118 // We can't optimize this if the malloc itself is used in a complex way,
1119 // for example, being stored into multiple globals. This allows the
1120 // malloc to be stored into the specified global, loaded, gep, icmp'd.
1121 // These are all things we could transform to using the global for.
1123 return false;
1124
1125 OptimizeGlobalAddressOfAllocation(GV, CI, AllocSize, InitVal, DL, TLI);
1126 return true;
1127}
1128
1129// Try to optimize globals based on the knowledge that only one value (besides
1130// its initializer) is ever stored to the global.
1131static bool
1133 const DataLayout &DL,
1135 // If we are dealing with a pointer global that is initialized to null and
1136 // only has one (non-null) value stored into it, then we can optimize any
1137 // users of the loaded value (often calls and loads) that would trap if the
1138 // value was null.
1139 if (GV->getInitializer()->getType()->isPointerTy() &&
1140 GV->getInitializer()->isNullValue() &&
1141 StoredOnceVal->getType()->isPointerTy() &&
1143 nullptr /* F */,
1145 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1146 // Optimize away any trapping uses of the loaded value.
1147 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI))
1148 return true;
1149 } else if (isAllocationFn(StoredOnceVal, GetTLI)) {
1150 if (auto *CI = dyn_cast<CallInst>(StoredOnceVal)) {
1151 auto *TLI = &GetTLI(*CI->getFunction());
1153 return true;
1154 }
1155 }
1156 }
1157
1158 return false;
1159}
1160
1161/// At this point, we have learned that the only two values ever stored into GV
1162/// are its initializer and OtherVal. See if we can shrink the global into a
1163/// boolean and select between the two values whenever it is used. This exposes
1164/// the values to other scalar optimizations.
1166 Type *GVElType = GV->getValueType();
1167
1168 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1169 // an FP value, pointer or vector, don't do this optimization because a select
1170 // between them is very expensive and unlikely to lead to later
1171 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1172 // where v1 and v2 both require constant pool loads, a big loss.
1173 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1174 GVElType->isFloatingPointTy() ||
1175 GVElType->isPointerTy() || GVElType->isVectorTy())
1176 return false;
1177
1178 // Walk the use list of the global seeing if all the uses are load or store.
1179 // If there is anything else, bail out.
1180 for (User *U : GV->users()) {
1181 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1182 return false;
1183 if (getLoadStoreType(U) != GVElType)
1184 return false;
1185 }
1186
1187 LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
1188
1189 // Create the new global, initializing it to false.
1191 false,
1194 GV->getName()+".b",
1195 GV->getThreadLocalMode(),
1196 GV->getType()->getAddressSpace());
1197 NewGV->copyAttributesFrom(GV);
1198 GV->getParent()->insertGlobalVariable(GV->getIterator(), NewGV);
1199
1200 Constant *InitVal = GV->getInitializer();
1201 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1202 "No reason to shrink to bool!");
1203
1205 GV->getDebugInfo(GVs);
1206
1207 // If initialized to zero and storing one into the global, we can use a cast
1208 // instead of a select to synthesize the desired value.
1209 bool IsOneZero = false;
1210 bool EmitOneOrZero = true;
1211 auto *CI = dyn_cast<ConstantInt>(OtherVal);
1212 if (CI && CI->getValue().getActiveBits() <= 64) {
1213 IsOneZero = InitVal->isNullValue() && CI->isOne();
1214
1215 auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer());
1216 if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
1217 uint64_t ValInit = CIInit->getZExtValue();
1218 uint64_t ValOther = CI->getZExtValue();
1219 uint64_t ValMinus = ValOther - ValInit;
1220
1221 for(auto *GVe : GVs){
1222 DIGlobalVariable *DGV = GVe->getVariable();
1223 DIExpression *E = GVe->getExpression();
1224 const DataLayout &DL = GV->getDataLayout();
1225 unsigned SizeInOctets = NewGV->getGlobalSize(DL);
1226
1227 // It is expected that the address of global optimized variable is on
1228 // top of the stack. After optimization, value of that variable will
1229 // be ether 0 for initial value or 1 for other value. The following
1230 // expression should return constant integer value depending on the
1231 // value at global object address:
1232 // val * (ValOther - ValInit) + ValInit:
1233 // DW_OP_deref DW_OP_constu <ValMinus>
1234 // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value
1236 dwarf::DW_OP_deref_size, SizeInOctets,
1237 dwarf::DW_OP_constu, ValMinus,
1238 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
1239 dwarf::DW_OP_plus};
1240 bool WithStackValue = true;
1241 E = DIExpression::prependOpcodes(E, Ops, WithStackValue);
1244 NewGV->addDebugInfo(DGVE);
1245 }
1246 EmitOneOrZero = false;
1247 }
1248 }
1249
1250 if (EmitOneOrZero) {
1251 // FIXME: This will only emit address for debugger on which will
1252 // be written only 0 or 1.
1253 for(auto *GV : GVs)
1254 NewGV->addDebugInfo(GV);
1255 }
1256
1257 while (!GV->use_empty()) {
1259 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1260 // Change the store into a boolean store.
1261 bool StoringOther = SI->getOperand(0) == OtherVal;
1262 // Only do this if we weren't storing a loaded value.
1263 Value *StoreVal;
1264 if (StoringOther || SI->getOperand(0) == InitVal) {
1265 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1266 StoringOther);
1267 } else {
1268 // Otherwise, we are storing a previously loaded copy. To do this,
1269 // change the copy from copying the original value to just copying the
1270 // bool.
1271 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1272
1273 // If we've already replaced the input, StoredVal will be a cast or
1274 // select instruction. If not, it will be a load of the original
1275 // global.
1276 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1277 assert(LI->getOperand(0) == GV && "Not a copy!");
1278 // Insert a new load, to preserve the saved value.
1279 StoreVal =
1280 new LoadInst(NewGV->getValueType(), NewGV, LI->getName() + ".b",
1281 false, Align(1), LI->getOrdering(),
1282 LI->getSyncScopeID(), LI->getIterator());
1283 cast<LoadInst>(StoreVal)->setDebugLoc(LI->getDebugLoc());
1284 } else {
1285 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1286 "This is not a form that we understand!");
1287 StoreVal = StoredVal->getOperand(0);
1288 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1289 }
1290 }
1291 StoreInst *NSI =
1292 new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(),
1293 SI->getSyncScopeID(), SI->getIterator());
1294 NSI->setDebugLoc(SI->getDebugLoc());
1295 } else {
1296 // Change the load into a load of bool then a select.
1297 LoadInst *LI = cast<LoadInst>(UI);
1298 LoadInst *NLI = new LoadInst(
1299 NewGV->getValueType(), NewGV, LI->getName() + ".b", false, Align(1),
1300 LI->getOrdering(), LI->getSyncScopeID(), LI->getIterator());
1301 Instruction *NSI;
1302 if (IsOneZero)
1303 NSI = new ZExtInst(NLI, LI->getType(), "", LI->getIterator());
1304 else {
1305 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI->getIterator());
1307 }
1308 NSI->takeName(LI);
1309 // Since LI is split into two instructions, NLI and NSI both inherit the
1310 // same DebugLoc
1311 NLI->setDebugLoc(LI->getDebugLoc());
1312 NSI->setDebugLoc(LI->getDebugLoc());
1313 LI->replaceAllUsesWith(NSI);
1314 }
1315 UI->eraseFromParent();
1316 }
1317
1318 // Retain the name of the old global variable. People who are debugging their
1319 // programs may expect these variables to be named the same.
1320 NewGV->takeName(GV);
1321 GV->eraseFromParent();
1322 return true;
1323}
1324
1325static bool
1327 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
1328 function_ref<void(Function &)> DeleteFnCallback = nullptr) {
1330
1331 if (!GV.isDiscardableIfUnused() && !GV.isDeclaration())
1332 return false;
1333
1334 if (const Comdat *C = GV.getComdat())
1335 if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C))
1336 return false;
1337
1338 bool Dead;
1339 if (auto *F = dyn_cast<Function>(&GV))
1340 Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead();
1341 else
1342 Dead = GV.use_empty();
1343 if (!Dead)
1344 return false;
1345
1346 LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n");
1347 if (auto *F = dyn_cast<Function>(&GV)) {
1348 if (DeleteFnCallback)
1349 DeleteFnCallback(*F);
1350 }
1352 GV.eraseFromParent();
1353 ++NumDeleted;
1354 return true;
1355}
1356
1358 const Function *F, GlobalValue *GV,
1359 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1360 // Find all uses of GV. We expect them all to be in F, and if we can't
1361 // identify any of the uses we bail out.
1362 //
1363 // On each of these uses, identify if the memory that GV points to is
1364 // used/required/live at the start of the function. If it is not, for example
1365 // if the first thing the function does is store to the GV, the GV can
1366 // possibly be demoted.
1367 //
1368 // We don't do an exhaustive search for memory operations - simply look
1369 // through bitcasts as they're quite common and benign.
1370 const DataLayout &DL = GV->getDataLayout();
1373 for (auto *U : GV->users()) {
1375 if (!I)
1376 return false;
1377 assert(I->getParent()->getParent() == F);
1378
1379 if (auto *LI = dyn_cast<LoadInst>(I))
1380 Loads.push_back(LI);
1381 else if (auto *SI = dyn_cast<StoreInst>(I))
1382 Stores.push_back(SI);
1383 else
1384 return false;
1385 }
1386
1387 // We have identified all uses of GV into loads and stores. Now check if all
1388 // of them are known not to depend on the value of the global at the function
1389 // entry point. We do this by ensuring that every load is dominated by at
1390 // least one store.
1391 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1392
1393 // The below check is quadratic. Check we're not going to do too many tests.
1394 // FIXME: Even though this will always have worst-case quadratic time, we
1395 // could put effort into minimizing the average time by putting stores that
1396 // have been shown to dominate at least one load at the beginning of the
1397 // Stores array, making subsequent dominance checks more likely to succeed
1398 // early.
1399 //
1400 // The threshold here is fairly large because global->local demotion is a
1401 // very powerful optimization should it fire.
1402 const unsigned Threshold = 100;
1403 if (Loads.size() * Stores.size() > Threshold)
1404 return false;
1405
1406 for (auto *L : Loads) {
1407 auto *LTy = L->getType();
1408 if (none_of(Stores, [&](const StoreInst *S) {
1409 auto *STy = S->getValueOperand()->getType();
1410 // The load is only dominated by the store if DomTree says so
1411 // and the number of bits loaded in L is less than or equal to
1412 // the number of bits stored in S.
1413 return DT.dominates(S, L) &&
1414 DL.getTypeStoreSize(LTy).getFixedValue() <=
1415 DL.getTypeStoreSize(STy).getFixedValue();
1416 }))
1417 return false;
1418 }
1419 // All loads have known dependences inside F, so the global can be localized.
1420 return true;
1421}
1422
1423// For a global variable with one store, if the store dominates any loads,
1424// those loads will always load the stored value (as opposed to the
1425// initializer), even in the presence of recursion.
1427 GlobalVariable *GV, const StoreInst *StoredOnceStore,
1428 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1429 const Value *StoredOnceValue = StoredOnceStore->getValueOperand();
1430 // We can do this optimization for non-constants in nosync + norecurse
1431 // functions, but globals used in exactly one norecurse functions are already
1432 // promoted to an alloca.
1433 if (!isa<Constant>(StoredOnceValue))
1434 return false;
1435 const Function *F = StoredOnceStore->getFunction();
1437 for (User *U : GV->users()) {
1438 if (auto *LI = dyn_cast<LoadInst>(U)) {
1439 if (LI->getFunction() == F &&
1440 LI->getType() == StoredOnceValue->getType() && LI->isSimple())
1441 Loads.push_back(LI);
1442 }
1443 }
1444 // Only compute DT if we have any loads to examine.
1445 bool MadeChange = false;
1446 if (!Loads.empty()) {
1447 auto &DT = LookupDomTree(*const_cast<Function *>(F));
1448 for (auto *LI : Loads) {
1449 if (DT.dominates(StoredOnceStore, LI)) {
1450 LI->replaceAllUsesWith(const_cast<Value *>(StoredOnceValue));
1451 LI->eraseFromParent();
1452 MadeChange = true;
1453 }
1454 }
1455 }
1456 return MadeChange;
1457}
1458
1459/// Analyze the specified global variable and optimize
1460/// it if possible. If we make a change, return true.
1461static bool
1465 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1466 auto &DL = GV->getDataLayout();
1467 // If this is a first class global and has only one accessing function and
1468 // this function is non-recursive, we replace the global with a local alloca
1469 // in this function.
1470 //
1471 // NOTE: It doesn't make sense to promote non-single-value types since we
1472 // are just replacing static memory to stack memory.
1473 //
1474 // If the global is in different address space, don't bring it to stack.
1475 if (!GS.HasMultipleAccessingFunctions &&
1476 GS.AccessingFunction &&
1478 GV->getType()->getAddressSpace() == DL.getAllocaAddrSpace() &&
1479 !GV->isExternallyInitialized() &&
1480 GS.AccessingFunction->doesNotRecurse() &&
1481 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV,
1482 LookupDomTree)) {
1483 const DataLayout &DL = GV->getDataLayout();
1484
1485 LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
1486 BasicBlock::iterator FirstI =
1487 GS.AccessingFunction->getEntryBlock().begin().getNonConst();
1488 Type *ElemTy = GV->getValueType();
1489 // FIXME: Pass Global's alignment when globals have alignment
1490 AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(),
1491 nullptr, GV->getName(), FirstI);
1493 if (!isa<UndefValue>(GV->getInitializer())) {
1494 auto *SI = new StoreInst(GV->getInitializer(), Alloca, FirstI);
1495 // FIXME: We're localizing a global and creating a store instruction for
1496 // the initial value of that global. Could we logically use the global
1497 // variable's (if one exists) line for this?
1498 SI->setDebugLoc(DebugLoc::getCompilerGenerated());
1499 }
1500
1501 GV->replaceAllUsesWith(Alloca);
1502 GV->eraseFromParent();
1503 ++NumLocalized;
1504 return true;
1505 }
1506
1507 bool Changed = false;
1508
1509 // If the global is never loaded (but may be stored to), it is dead.
1510 // Delete it now.
1511 if (!GS.IsLoaded) {
1512 LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
1513
1514 if (isLeakCheckerRoot(GV)) {
1515 // Delete any constant stores to the global.
1516 Changed = CleanupPointerRootUsers(GV, GetTLI);
1517 } else {
1518 // Delete any stores we can find to the global. We may not be able to
1519 // make it completely dead though.
1521 }
1522
1523 // If the global is dead now, delete it.
1524 if (GV->use_empty()) {
1525 GV->eraseFromParent();
1526 ++NumDeleted;
1527 Changed = true;
1528 }
1529 return Changed;
1530
1531 }
1532 if (GS.StoredType <= GlobalStatus::InitializerStored) {
1533 LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
1534
1535 // Don't actually mark a global constant if it's atomic because atomic loads
1536 // are implemented by a trivial cmpxchg in some edge-cases and that usually
1537 // requires write access to the variable even if it's not actually changed.
1538 if (GS.Ordering == AtomicOrdering::NotAtomic) {
1539 assert(!GV->isConstant() && "Expected a non-constant global");
1540 GV->setConstant(true);
1541 Changed = true;
1542 }
1543
1544 // Clean up any obviously simplifiable users now.
1546
1547 // If the global is dead now, just nuke it.
1548 if (GV->use_empty()) {
1549 LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1550 << "all users and delete global!\n");
1551 GV->eraseFromParent();
1552 ++NumDeleted;
1553 return true;
1554 }
1555
1556 // Fall through to the next check; see if we can optimize further.
1557 ++NumMarked;
1558 }
1559 if (!GV->getInitializer()->getType()->isSingleValueType()) {
1560 const DataLayout &DL = GV->getDataLayout();
1561 if (SRAGlobal(GV, DL))
1562 return true;
1563 }
1564 Value *StoredOnceValue = GS.getStoredOnceValue();
1565 if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) {
1566 Function &StoreFn =
1567 const_cast<Function &>(*GS.StoredOnceStore->getFunction());
1568 bool CanHaveNonUndefGlobalInitializer =
1569 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace(
1570 GV->getType()->getAddressSpace());
1571 // If the initial value for the global was an undef value, and if only
1572 // one other value was stored into it, we can just change the
1573 // initializer to be the stored value, then delete all stores to the
1574 // global. This allows us to mark it constant.
1575 // This is restricted to address spaces that allow globals to have
1576 // initializers. NVPTX, for example, does not support initializers for
1577 // shared memory (AS 3).
1578 auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue);
1579 if (SOVConstant && isa<UndefValue>(GV->getInitializer()) &&
1580 DL.getTypeAllocSize(SOVConstant->getType()).getFixedValue() ==
1581 GV->getGlobalSize(DL) &&
1582 CanHaveNonUndefGlobalInitializer) {
1583 if (SOVConstant->getType() == GV->getValueType()) {
1584 // Change the initializer in place.
1585 GV->setInitializer(SOVConstant);
1586 } else {
1587 // Create a new global with adjusted type.
1588 auto *NGV = new GlobalVariable(
1589 *GV->getParent(), SOVConstant->getType(), GV->isConstant(),
1590 GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(),
1591 GV->getAddressSpace());
1592 NGV->takeName(GV);
1593 NGV->copyAttributesFrom(GV);
1594 GV->replaceAllUsesWith(NGV);
1595 GV->eraseFromParent();
1596 GV = NGV;
1597 }
1598
1599 // Clean up any obviously simplifiable users now.
1601
1602 if (GV->use_empty()) {
1603 LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1604 << "simplify all users and delete global!\n");
1605 GV->eraseFromParent();
1606 ++NumDeleted;
1607 }
1608 ++NumSubstitute;
1609 return true;
1610 }
1611
1612 // Try to optimize globals based on the knowledge that only one value
1613 // (besides its initializer) is ever stored to the global.
1614 if (optimizeOnceStoredGlobal(GV, StoredOnceValue, DL, GetTLI))
1615 return true;
1616
1617 // Try to forward the store to any loads. If we have more than one store, we
1618 // may have a store of the initializer between StoredOnceStore and a load.
1619 if (GS.NumStores == 1)
1620 if (forwardStoredOnceStore(GV, GS.StoredOnceStore, LookupDomTree))
1621 return true;
1622
1623 // Otherwise, if the global was not a boolean, we can shrink it to be a
1624 // boolean. Skip this optimization for AS that doesn't allow an initializer.
1625 if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic &&
1627 CanHaveNonUndefGlobalInitializer)) {
1628 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1629 ++NumShrunkToBool;
1630 return true;
1631 }
1632 }
1633 }
1634
1635 return Changed;
1636}
1637
1638/// Analyze the specified global variable and optimize it if possible. If we
1639/// make a change, return true.
1640static bool
1644 function_ref<DominatorTree &(Function &)> LookupDomTree) {
1645 if (GV.getName().starts_with("llvm."))
1646 return false;
1647
1648 GlobalStatus GS;
1649
1650 if (GlobalStatus::analyzeGlobal(&GV, GS))
1651 return false;
1652
1653 bool Changed = false;
1654 if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) {
1655 auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global
1657 if (NewUnnamedAddr != GV.getUnnamedAddr()) {
1658 GV.setUnnamedAddr(NewUnnamedAddr);
1659 NumUnnamed++;
1660 Changed = true;
1661 }
1662 }
1663
1664 // Do more involved optimizations if the global is internal.
1665 if (!GV.hasLocalLinkage())
1666 return Changed;
1667
1668 auto *GVar = dyn_cast<GlobalVariable>(&GV);
1669 if (!GVar)
1670 return Changed;
1671
1672 if (GVar->isConstant() || !GVar->hasInitializer())
1673 return Changed;
1674
1675 return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) ||
1676 Changed;
1677}
1678
1679/// Walk all of the direct calls of the specified function, changing them to
1680/// FastCC.
1682 for (User *U : F->users())
1683 if (auto *Call = dyn_cast<CallBase>(U))
1684 if (Call->getCalledOperand() == F)
1685 Call->setCallingConv(CallingConv::Fast);
1686}
1687
1688static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs,
1690 unsigned AttrIndex;
1691 if (Attrs.hasAttrSomewhere(A, &AttrIndex))
1692 return Attrs.removeAttributeAtIndex(C, AttrIndex, A);
1693 return Attrs;
1694}
1695
1697 F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A));
1698 for (User *U : F->users()) {
1699 CallBase *CB = cast<CallBase>(U);
1700 CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A));
1701 }
1702}
1703
1704/// Return true if this is a calling convention that we'd like to change. The
1705/// idea here is that we don't want to mess with the convention if the user
1706/// explicitly requested something with performance implications like coldcc,
1707/// GHC, or anyregcc.
1709 CallingConv::ID CC = F->getCallingConv();
1710
1711 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
1712 if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall)
1713 return false;
1714
1715 if (!F->canChangeSignature())
1716 return false;
1717
1718 if (F->isVarArg())
1719 return false;
1720
1721 // FIXME: Change CC for the whole chain of musttail calls when possible.
1722 //
1723 // Can't change CC of the function that either has musttail calls, or is a
1724 // musttail callee itself
1725 for (User *U : F->users()) {
1727 if (!CI)
1728 continue;
1729
1730 if (CI->isMustTailCall())
1731 return false;
1732 }
1733
1734 for (BasicBlock &BB : *F)
1735 if (BB.getTerminatingMustTailCall())
1736 return false;
1737
1738 return !F->hasAddressTaken();
1739}
1740
1743 ChangeableCCCacheTy &ChangeableCCCache) {
1744 auto Res = ChangeableCCCache.try_emplace(F, false);
1745 if (Res.second)
1746 Res.first->second = hasChangeableCCImpl(F);
1747 return Res.first->second;
1748}
1749
1750/// Return true if the block containing the call site has a BlockFrequency of
1751/// less than ColdCCRelFreq% of the entry block.
1752static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) {
1753 const BranchProbability ColdProb(ColdCCRelFreq, 100);
1754 auto *CallSiteBB = CB.getParent();
1755 auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB);
1756 auto CallerEntryFreq =
1757 CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock()));
1758 return CallSiteFreq < CallerEntryFreq * ColdProb;
1759}
1760
1761// This function checks if the input function F is cold at all call sites. It
1762// also looks each call site's containing function, returning false if the
1763// caller function contains other non cold calls. The input vector AllCallsCold
1764// contains a list of functions that only have call sites in cold blocks.
1765static bool
1768 const std::vector<Function *> &AllCallsCold) {
1769
1770 if (F.user_empty())
1771 return false;
1772
1773 for (User *U : F.users()) {
1775 if (!CB || CB->getCalledOperand() != &F)
1776 continue;
1777 Function *CallerFunc = CB->getParent()->getParent();
1778 BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc);
1779 if (!isColdCallSite(*CB, CallerBFI))
1780 return false;
1781 if (!llvm::is_contained(AllCallsCold, CallerFunc))
1782 return false;
1783 }
1784 return true;
1785}
1786
1788 for (User *U : F->users())
1789 if (auto *Call = dyn_cast<CallBase>(U))
1790 if (Call->getCalledOperand() == F)
1791 Call->setCallingConv(CallingConv::Cold);
1792}
1793
1794// This function iterates over all the call instructions in the input Function
1795// and checks that all call sites are in cold blocks and are allowed to use the
1796// coldcc calling convention.
1797static bool
1800 ChangeableCCCacheTy &ChangeableCCCache) {
1801 for (BasicBlock &BB : F) {
1802 for (Instruction &I : BB) {
1803 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1804 // Skip over isline asm instructions since they aren't function calls.
1805 if (CI->isInlineAsm())
1806 continue;
1807 Function *CalledFn = CI->getCalledFunction();
1808 if (!CalledFn)
1809 return false;
1810 // Skip over intrinsics since they won't remain as function calls.
1811 // Important to do this check before the linkage check below so we
1812 // won't bail out on debug intrinsics, possibly making the generated
1813 // code dependent on the presence of debug info.
1814 if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic)
1815 continue;
1816 if (!CalledFn->hasLocalLinkage())
1817 return false;
1818 // Check if it's valid to use coldcc calling convention.
1819 if (!hasChangeableCC(CalledFn, ChangeableCCCache))
1820 return false;
1821 BlockFrequencyInfo &CallerBFI = GetBFI(F);
1822 if (!isColdCallSite(*CI, CallerBFI))
1823 return false;
1824 }
1825 }
1826 }
1827 return true;
1828}
1829
1831 for (User *U : F->users()) {
1832 CallBase *CB = cast<CallBase>(U);
1833 if (CB->isMustTailCall())
1834 return true;
1835 }
1836 return false;
1837}
1838
1840 for (User *U : F->users())
1841 if (isa<InvokeInst>(U))
1842 return true;
1843 return false;
1844}
1845
1847 RemoveAttribute(F, Attribute::Preallocated);
1848
1849 auto *M = F->getParent();
1850
1851 IRBuilder<> Builder(M->getContext());
1852
1853 // Cannot modify users() while iterating over it, so make a copy.
1854 SmallVector<User *, 4> PreallocatedCalls(F->users());
1855 for (User *U : PreallocatedCalls) {
1857 if (!CB)
1858 continue;
1859
1860 assert(
1861 !CB->isMustTailCall() &&
1862 "Shouldn't call RemotePreallocated() on a musttail preallocated call");
1863 // Create copy of call without "preallocated" operand bundle.
1865 CB->getOperandBundlesAsDefs(OpBundles);
1866 CallBase *PreallocatedSetup = nullptr;
1867 for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) {
1868 if (It->getTag() == "preallocated") {
1869 PreallocatedSetup = cast<CallBase>(*It->input_begin());
1870 OpBundles.erase(It);
1871 break;
1872 }
1873 }
1874 assert(PreallocatedSetup && "Did not find preallocated bundle");
1875 uint64_t ArgCount =
1876 cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue();
1877
1878 assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
1879 "Unknown indirect call type");
1880 CallBase *NewCB = CallBase::Create(CB, OpBundles, CB->getIterator());
1881 CB->replaceAllUsesWith(NewCB);
1882 NewCB->takeName(CB);
1883 CB->eraseFromParent();
1884
1885 Builder.SetInsertPoint(PreallocatedSetup);
1886 auto *StackSave = Builder.CreateStackSave();
1887 Builder.SetInsertPoint(NewCB->getNextNode());
1888 Builder.CreateStackRestore(StackSave);
1889
1890 // Replace @llvm.call.preallocated.arg() with alloca.
1891 // Cannot modify users() while iterating over it, so make a copy.
1892 // @llvm.call.preallocated.arg() can be called with the same index multiple
1893 // times. So for each @llvm.call.preallocated.arg(), we see if we have
1894 // already created a Value* for the index, and if not, create an alloca and
1895 // bitcast right after the @llvm.call.preallocated.setup() so that it
1896 // dominates all uses.
1897 SmallVector<Value *, 2> ArgAllocas(ArgCount);
1898 SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users());
1899 for (auto *User : PreallocatedArgs) {
1900 auto *UseCall = cast<CallBase>(User);
1901 assert(UseCall->getCalledFunction()->getIntrinsicID() ==
1902 Intrinsic::call_preallocated_arg &&
1903 "preallocated token use was not a llvm.call.preallocated.arg");
1904 uint64_t AllocArgIndex =
1905 cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue();
1906 Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
1907 if (!AllocaReplacement) {
1908 auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
1909 auto *ArgType =
1910 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType();
1911 auto *InsertBefore = PreallocatedSetup->getNextNode();
1912 Builder.SetInsertPoint(InsertBefore);
1913 auto *Alloca =
1914 Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg");
1915 ArgAllocas[AllocArgIndex] = Alloca;
1916 AllocaReplacement = Alloca;
1917 }
1918
1919 UseCall->replaceAllUsesWith(AllocaReplacement);
1920 UseCall->eraseFromParent();
1921 }
1922 // Remove @llvm.call.preallocated.setup().
1923 cast<Instruction>(PreallocatedSetup)->eraseFromParent();
1924 }
1925}
1926
1927static bool
1932 function_ref<DominatorTree &(Function &)> LookupDomTree,
1933 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats,
1934 function_ref<void(Function &F)> ChangedCFGCallback,
1935 function_ref<void(Function &F)> DeleteFnCallback) {
1936
1937 bool Changed = false;
1938
1939 ChangeableCCCacheTy ChangeableCCCache;
1940 std::vector<Function *> AllCallsCold;
1942 if (hasOnlyColdCalls(F, GetBFI, ChangeableCCCache))
1943 AllCallsCold.push_back(&F);
1944
1945 // Optimize functions.
1947 // Don't perform global opt pass on naked functions; we don't want fast
1948 // calling conventions for naked functions.
1949 if (F.hasFnAttribute(Attribute::Naked))
1950 continue;
1951
1952 // Functions without names cannot be referenced outside this module.
1953 if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage())
1954 F.setLinkage(GlobalValue::InternalLinkage);
1955
1956 if (deleteIfDead(F, NotDiscardableComdats, DeleteFnCallback)) {
1957 Changed = true;
1958 continue;
1959 }
1960
1961 // LLVM's definition of dominance allows instructions that are cyclic
1962 // in unreachable blocks, e.g.:
1963 // %pat = select i1 %condition, @global, i16* %pat
1964 // because any instruction dominates an instruction in a block that's
1965 // not reachable from entry.
1966 // So, remove unreachable blocks from the function, because a) there's
1967 // no point in analyzing them and b) GlobalOpt should otherwise grow
1968 // some more complicated logic to break these cycles.
1969 // Notify the analysis manager that we've modified the function's CFG.
1970 if (!F.isDeclaration()) {
1972 Changed = true;
1973 ChangedCFGCallback(F);
1974 }
1975 }
1976
1977 Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree);
1978
1979 if (!F.hasLocalLinkage())
1980 continue;
1981
1982 // Ensure function definition is available for interprocedural analysis.
1983 if (!F.isDefinitionExact())
1984 continue;
1985
1986 // If we have an inalloca parameter that we can safely remove the
1987 // inalloca attribute from, do so. This unlocks optimizations that
1988 // wouldn't be safe in the presence of inalloca.
1989 // FIXME: We should also hoist alloca affected by this to the entry
1990 // block if possible.
1991 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
1992 !F.hasAddressTaken() && !hasMustTailCallers(&F) && !F.isVarArg()) {
1993 RemoveAttribute(&F, Attribute::InAlloca);
1994 Changed = true;
1995 }
1996
1997 // FIXME: handle invokes
1998 // FIXME: handle musttail
1999 if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
2000 if (!F.hasAddressTaken() && !hasMustTailCallers(&F) &&
2001 !hasInvokeCallers(&F)) {
2003 Changed = true;
2004 }
2005 continue;
2006 }
2007
2008 if (hasChangeableCC(&F, ChangeableCCCache)) {
2009 NumInternalFunc++;
2010 TargetTransformInfo &TTI = GetTTI(F);
2011 // Change the calling convention to coldcc if either stress testing is
2012 // enabled or the target would like to use coldcc on functions which are
2013 // cold at all call sites and the callers contain no other non coldcc
2014 // calls.
2016 (TTI.useColdCCForColdCall(F) &&
2017 isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) {
2018 ChangeableCCCache.erase(&F);
2019 F.setCallingConv(CallingConv::Cold);
2021 Changed = true;
2022 NumColdCC++;
2023 }
2024 }
2025
2026 if (hasChangeableCC(&F, ChangeableCCCache)) {
2027 // If this function has a calling convention worth changing, is not a
2028 // varargs function, is only called directly, and is supported by the
2029 // target, promote it to use the Fast calling convention.
2030 TargetTransformInfo &TTI = GetTTI(F);
2031 if (TTI.useFastCCForInternalCall(F)) {
2032 F.setCallingConv(CallingConv::Fast);
2034 ++NumFastCallFns;
2035 Changed = true;
2036 }
2037 }
2038
2039 if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) &&
2040 !F.hasAddressTaken()) {
2041 // The function is not used by a trampoline intrinsic, so it is safe
2042 // to remove the 'nest' attribute.
2043 RemoveAttribute(&F, Attribute::Nest);
2044 ++NumNestRemoved;
2045 Changed = true;
2046 }
2047 }
2048 return Changed;
2049}
2050
2051static bool
2055 function_ref<DominatorTree &(Function &)> LookupDomTree,
2056 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2057 bool Changed = false;
2058
2059 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
2060 // Global variables without names cannot be referenced outside this module.
2061 if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage())
2063 // Simplify the initializer.
2064 if (GV.hasInitializer()) {
2065 const Constant *C = GV.getInitializer();
2066 auto &DL = M.getDataLayout();
2067 // TLI is not used in the case of a Constant, so use default nullptr
2068 // for that optional parameter, since we don't have a Function to
2069 // provide GetTLI anyway.
2070 Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr);
2071 if (New != C)
2072 GV.setInitializer(New);
2073 }
2074
2075 if (deleteIfDead(GV, NotDiscardableComdats)) {
2076 Changed = true;
2077 continue;
2078 }
2079
2080 Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree);
2081 }
2082 return Changed;
2083}
2084
2085/// Evaluate static constructors in the function, if we can. Return true if we
2086/// can, false otherwise.
2088 TargetLibraryInfo *TLI) {
2089 // Skip external functions.
2090 if (F->isDeclaration())
2091 return false;
2092 // Call the function.
2093 Evaluator Eval(DL, TLI);
2094 Constant *RetValDummy;
2095 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2097
2098 if (EvalSuccess) {
2099 ++NumCtorsEvaluated;
2100
2101 // We succeeded at evaluation: commit the result.
2102 auto NewInitializers = Eval.getMutatedInitializers();
2103 LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2104 << F->getName() << "' to " << NewInitializers.size()
2105 << " stores.\n");
2106 for (const auto &Pair : NewInitializers)
2107 Pair.first->setInitializer(Pair.second);
2108 for (GlobalVariable *GV : Eval.getInvariants())
2109 GV->setConstant(true);
2110 }
2111
2112 return EvalSuccess;
2113}
2114
2115static int compareNames(Constant *const *A, Constant *const *B) {
2116 Value *AStripped = (*A)->stripPointerCasts();
2117 Value *BStripped = (*B)->stripPointerCasts();
2118 return AStripped->getName().compare(BStripped->getName());
2119}
2120
2123 if (Init.empty()) {
2124 V.eraseFromParent();
2125 return;
2126 }
2127
2128 // Get address space of pointers in the array of pointers.
2129 const Type *UsedArrayType = V.getValueType();
2130 const auto *VAT = cast<ArrayType>(UsedArrayType);
2131 const auto *VEPT = cast<PointerType>(VAT->getArrayElementType());
2132
2133 // Type of pointer to the array of pointers.
2134 PointerType *PtrTy =
2135 PointerType::get(V.getContext(), VEPT->getAddressSpace());
2136
2138 for (GlobalValue *GV : Init) {
2140 UsedArray.push_back(Cast);
2141 }
2142
2143 // Sort to get deterministic order.
2144 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2145 ArrayType *ATy = ArrayType::get(PtrTy, UsedArray.size());
2146
2147 Module *M = V.getParent();
2148 V.removeFromParent();
2150 *M, ATy, false, GlobalValue::AppendingLinkage,
2151 ConstantArray::get(ATy, UsedArray), "", nullptr,
2152 GlobalVariable::NotThreadLocal, V.getType()->getAddressSpace());
2153 NV->takeName(&V);
2154 NV->setSection("llvm.metadata");
2155 delete &V;
2156}
2157
2158namespace {
2159
2160/// An easy to access representation of llvm.used and llvm.compiler.used.
2161class LLVMUsed {
2162 SmallPtrSet<GlobalValue *, 4> Used;
2163 SmallPtrSet<GlobalValue *, 4> CompilerUsed;
2164 GlobalVariable *UsedV;
2165 GlobalVariable *CompilerUsedV;
2166
2167public:
2168 LLVMUsed(Module &M) {
2170 UsedV = collectUsedGlobalVariables(M, Vec, false);
2171 Used = {llvm::from_range, Vec};
2172 Vec.clear();
2173 CompilerUsedV = collectUsedGlobalVariables(M, Vec, true);
2174 CompilerUsed = {llvm::from_range, Vec};
2175 }
2176
2177 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator;
2178 using used_iterator_range = iterator_range<iterator>;
2179
2180 iterator usedBegin() { return Used.begin(); }
2181 iterator usedEnd() { return Used.end(); }
2182
2183 used_iterator_range used() {
2184 return used_iterator_range(usedBegin(), usedEnd());
2185 }
2186
2187 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2188 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2189
2190 used_iterator_range compilerUsed() {
2191 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2192 }
2193
2194 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2195
2196 bool compilerUsedCount(GlobalValue *GV) const {
2197 return CompilerUsed.count(GV);
2198 }
2199
2200 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2201 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2202 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2203
2204 bool compilerUsedInsert(GlobalValue *GV) {
2205 return CompilerUsed.insert(GV).second;
2206 }
2207
2208 void syncVariablesAndSets() {
2209 if (UsedV)
2210 setUsedInitializer(*UsedV, Used);
2211 if (CompilerUsedV)
2212 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2213 }
2214};
2215
2216} // end anonymous namespace
2217
2218static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2219 if (GA.use_empty()) // No use at all.
2220 return false;
2221
2222 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2223 "We should have removed the duplicated "
2224 "element from llvm.compiler.used");
2225 if (!GA.hasOneUse())
2226 // Strictly more than one use. So at least one is not in llvm.used and
2227 // llvm.compiler.used.
2228 return true;
2229
2230 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
2231 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2232}
2233
2234static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U) {
2235 if (!GV.hasLocalLinkage())
2236 return true;
2237
2238 return U.usedCount(&GV) || U.compilerUsedCount(&GV);
2239}
2240
2241static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2242 bool &RenameTarget) {
2243 if (GA.isWeakForLinker())
2244 return false;
2245
2246 RenameTarget = false;
2247 bool Ret = false;
2248 if (hasUseOtherThanLLVMUsed(GA, U))
2249 Ret = true;
2250
2251 // If the alias is externally visible, we may still be able to simplify it.
2252 if (!mayHaveOtherReferences(GA, U))
2253 return Ret;
2254
2255 // If the aliasee has internal linkage and no other references (e.g.,
2256 // @llvm.used, @llvm.compiler.used), give it the name and linkage of the
2257 // alias, and delete the alias. This turns:
2258 // define internal ... @f(...)
2259 // @a = alias ... @f
2260 // into:
2261 // define ... @a(...)
2262 Constant *Aliasee = GA.getAliasee();
2265 return Ret;
2266
2267 RenameTarget = true;
2268 return true;
2269}
2270
2271static bool
2273 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2274 bool Changed = false;
2275 LLVMUsed Used(M);
2276
2277 for (GlobalValue *GV : Used.used())
2278 Used.compilerUsedErase(GV);
2279
2280 // Return whether GV is explicitly or implicitly dso_local and not replaceable
2281 // by another definition in the current linkage unit.
2282 auto IsModuleLocal = [](GlobalValue &GV) {
2284 (GV.isDSOLocal() || GV.isImplicitDSOLocal());
2285 };
2286
2287 for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) {
2288 // Aliases without names cannot be referenced outside this module.
2289 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage())
2290 J.setLinkage(GlobalValue::InternalLinkage);
2291
2292 if (deleteIfDead(J, NotDiscardableComdats)) {
2293 Changed = true;
2294 continue;
2295 }
2296
2297 // If the alias can change at link time, nothing can be done - bail out.
2298 if (!IsModuleLocal(J))
2299 continue;
2300
2301 Constant *Aliasee = J.getAliasee();
2303 // We can't trivially replace the alias with the aliasee if the aliasee is
2304 // non-trivial in some way. We also can't replace the alias with the aliasee
2305 // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible
2306 // alias can be used to access the definition as if preemption did not
2307 // happen.
2308 // TODO: Try to handle non-zero GEPs of local aliasees.
2309 if (!Target || !IsModuleLocal(*Target))
2310 continue;
2311
2312 Target->removeDeadConstantUsers();
2313
2314 // Make all users of the alias use the aliasee instead.
2315 bool RenameTarget;
2316 if (!hasUsesToReplace(J, Used, RenameTarget))
2317 continue;
2318
2319 J.replaceAllUsesWith(Aliasee);
2320 ++NumAliasesResolved;
2321 Changed = true;
2322
2323 if (RenameTarget) {
2324 // Give the aliasee the name, linkage and other attributes of the alias.
2325 Target->takeName(&J);
2326 Target->setLinkage(J.getLinkage());
2327 Target->setDSOLocal(J.isDSOLocal());
2328 Target->setVisibility(J.getVisibility());
2329 Target->setDLLStorageClass(J.getDLLStorageClass());
2330
2331 if (Used.usedErase(&J))
2332 Used.usedInsert(Target);
2333
2334 if (Used.compilerUsedErase(&J))
2335 Used.compilerUsedInsert(Target);
2336 } else if (mayHaveOtherReferences(J, Used))
2337 continue;
2338
2339 // Delete the alias.
2340 M.eraseAlias(&J);
2341 ++NumAliasesRemoved;
2342 Changed = true;
2343 }
2344
2345 Used.syncVariablesAndSets();
2346
2347 return Changed;
2348}
2349
2350static Function *
2353 LibFunc Func) {
2354 // Hack to get a default TLI before we have actual Function.
2355 auto FuncIter = M.begin();
2356 if (FuncIter == M.end())
2357 return nullptr;
2358 auto *TLI = &GetTLI(*FuncIter);
2359
2360 if (!TLI->has(Func))
2361 return nullptr;
2362
2363 Function *Fn = M.getFunction(TLI->getName(Func));
2364 if (!Fn)
2365 return nullptr;
2366
2367 // Now get the actual TLI for Fn.
2368 TLI = &GetTLI(*Fn);
2369
2370 // Make sure that the function has the correct prototype.
2371 if (TLI->getLibFunc(*Fn) != Func)
2372 return nullptr;
2373
2374 return Fn;
2375}
2376
2377/// Returns whether the given function is an empty C++ destructor or atexit
2378/// handler and can therefore be eliminated. Note that we assume that other
2379/// optimization passes have already simplified the code so we simply check for
2380/// 'ret'.
2381static bool IsEmptyAtExitFunction(const Function &Fn) {
2382 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
2383 // nounwind, but that doesn't seem worth doing.
2384 if (Fn.isDeclaration())
2385 return false;
2386
2387 for (const auto &I : Fn.getEntryBlock()) {
2388 if (I.isDebugOrPseudoInst())
2389 continue;
2390 if (isa<ReturnInst>(I))
2391 return true;
2392 break;
2393 }
2394 return false;
2395}
2396
2397static bool OptimizeEmptyGlobalAtExitDtors(Function *CXAAtExitFn, bool isCXX) {
2398 /// Itanium C++ ABI p3.3.5:
2399 ///
2400 /// After constructing a global (or local static) object, that will require
2401 /// destruction on exit, a termination function is registered as follows:
2402 ///
2403 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2404 ///
2405 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2406 /// call f(p) when DSO d is unloaded, before all such termination calls
2407 /// registered before this one. It returns zero if registration is
2408 /// successful, nonzero on failure.
2409
2410 // This pass will look for calls to __cxa_atexit or atexit where the function
2411 // is trivial and remove them.
2412 bool Changed = false;
2413
2414 for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) {
2415 // We're only interested in calls. Theoretically, we could handle invoke
2416 // instructions as well, but neither llvm-gcc nor clang generate invokes
2417 // to __cxa_atexit.
2419 if (!CI)
2420 continue;
2421
2422 Function *DtorFn =
2424 if (!DtorFn || !IsEmptyAtExitFunction(*DtorFn))
2425 continue;
2426
2427 // Just remove the call.
2429 CI->eraseFromParent();
2430
2431 if (isCXX)
2432 ++NumCXXDtorsRemoved;
2433 else
2434 ++NumAtExitRemoved;
2435
2436 Changed |= true;
2437 }
2438
2439 return Changed;
2440}
2441
2443 if (IF.isInterposable())
2444 return nullptr;
2445
2447 if (!Resolver)
2448 return nullptr;
2449
2450 if (Resolver->isInterposable())
2451 return nullptr;
2452
2453 // Only handle functions that have been optimized into a single basic block.
2454 auto It = Resolver->begin();
2455 if (++It != Resolver->end())
2456 return nullptr;
2457
2458 BasicBlock &BB = Resolver->getEntryBlock();
2459
2460 if (any_of(BB, [](Instruction &I) { return I.mayHaveSideEffects(); }))
2461 return nullptr;
2462
2463 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
2464 if (!Ret)
2465 return nullptr;
2466
2467 return dyn_cast<Function>(Ret->getReturnValue());
2468}
2469
2470/// Find IFuncs that have resolvers that always point at the same statically
2471/// known callee, and replace their callers with a direct call.
2473 bool Changed = false;
2474 for (GlobalIFunc &IF : M.ifuncs())
2476 if (!IF.use_empty() &&
2477 (!Callee->isDeclaration() ||
2478 none_of(IF.users(), [](User *U) { return isa<GlobalAlias>(U); }))) {
2479 IF.replaceAllUsesWith(Callee);
2480 NumIFuncsResolved++;
2481 Changed = true;
2482 }
2483 return Changed;
2484}
2485
2486static bool
2488 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2489 bool Changed = false;
2490 for (GlobalIFunc &IF : make_early_inc_range(M.ifuncs()))
2491 if (deleteIfDead(IF, NotDiscardableComdats)) {
2492 NumIFuncsDeleted++;
2493 Changed = true;
2494 }
2495 return Changed;
2496}
2497
2498// Follows the use-def chain of \p V backwards until it finds a Function,
2499// in which case it collects in \p Versions. Return true on successful
2500// use-def chain traversal, false otherwise.
2501static bool
2504 if (auto *F = dyn_cast<Function>(V)) {
2505 if (!GetTTI(*F).isMultiversionedFunction(*F))
2506 return false;
2507 Versions.push_back(F);
2508 } else if (auto *Sel = dyn_cast<SelectInst>(V)) {
2509 if (!collectVersions(Sel->getTrueValue(), Versions, GetTTI))
2510 return false;
2511 if (!collectVersions(Sel->getFalseValue(), Versions, GetTTI))
2512 return false;
2513 } else if (auto *Phi = dyn_cast<PHINode>(V)) {
2514 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
2515 if (!collectVersions(Phi->getIncomingValue(I), Versions, GetTTI))
2516 return false;
2517 } else {
2518 // Unknown instruction type. Bail.
2519 return false;
2520 }
2521 return true;
2522}
2523
2524// Try to statically resolve calls to versioned functions when possible. First
2525// we identify the function versions which are associated with an IFUNC symbol.
2526// We do that by examining the resolver function of the IFUNC. Once we have
2527// collected all the function versions, we sort them in decreasing priority
2528// order. This is necessary for determining the most suitable callee version
2529// for each caller version. We then collect all the callsites to versioned
2530// functions. The static resolution is performed by comparing the feature sets
2531// between callers and callees. Specifically:
2532// * Start a walk over caller and callee lists simultaneously in order of
2533// decreasing priority.
2534// * Statically resolve calls from the current caller to the current callee,
2535// iff the caller feature bits are a superset of the callee feature bits.
2536// * For FMV callers, as long as the caller feature bits are a subset of the
2537// callee feature bits, advance to the next callee. This effectively prevents
2538// considering the current callee as a candidate for static resolution by
2539// following callers (explanation: preceding callers would not have been
2540// selected in a hypothetical runtime execution).
2541// * Advance to the next caller.
2542//
2543// Presentation in EuroLLVM2025:
2544// https://www.youtube.com/watch?v=k54MFimPz-A&t=867s
2547 bool Changed = false;
2548
2549 // Map containing the feature bits for a given function.
2550 DenseMap<Function *, APInt> FeatureMask;
2551 // Map containing the priority bits for a given function.
2552 DenseMap<Function *, APInt> PriorityMask;
2553 // Map containing all the function versions corresponding to an IFunc symbol.
2555 // Map containing the IFunc symbol a function is version of.
2557 // List of all the interesting IFuncs found in the module.
2559
2560 for (GlobalIFunc &IF : M.ifuncs()) {
2561 LLVM_DEBUG(dbgs() << "Examining IFUNC " << IF.getName() << "\n");
2562
2563 if (IF.isInterposable())
2564 continue;
2565
2566 Function *Resolver = IF.getResolverFunction();
2567 if (!Resolver)
2568 continue;
2569
2570 if (Resolver->isInterposable())
2571 continue;
2572
2573 SmallVector<Function *> Versions;
2574 // Discover the versioned functions.
2575 if (any_of(*Resolver, [&](BasicBlock &BB) {
2576 if (auto *Ret = dyn_cast_or_null<ReturnInst>(BB.getTerminator()))
2577 if (!collectVersions(Ret->getReturnValue(), Versions, GetTTI))
2578 return true;
2579 return false;
2580 }))
2581 continue;
2582
2583 if (Versions.empty())
2584 continue;
2585
2586 for (Function *V : Versions) {
2587 VersionOf.insert({V, &IF});
2588 auto [FeatIt, FeatInserted] = FeatureMask.try_emplace(V);
2589 if (FeatInserted)
2590 FeatIt->second = GetTTI(*V).getFeatureMask(*V);
2591 auto [PriorIt, PriorInserted] = PriorityMask.try_emplace(V);
2592 if (PriorInserted)
2593 PriorIt->second = GetTTI(*V).getPriorityMask(*V);
2594 }
2595
2596 // Sort function versions in decreasing priority order.
2597 sort(Versions, [&](auto *LHS, auto *RHS) {
2598 return PriorityMask[LHS].ugt(PriorityMask[RHS]);
2599 });
2600
2601 IFuncs.push_back(&IF);
2602 VersionedFuncs.try_emplace(&IF, std::move(Versions));
2603 }
2604
2605 for (GlobalIFunc *CalleeIF : IFuncs) {
2606 SmallVector<Function *> NonFMVCallers;
2607 DenseSet<GlobalIFunc *> CallerIFuncs;
2609
2610 // Find the callsites.
2611 for (User *U : CalleeIF->users()) {
2612 if (auto *CB = dyn_cast<CallBase>(U)) {
2613 if (CB->getCalledOperand() == CalleeIF) {
2614 Function *Caller = CB->getFunction();
2615 GlobalIFunc *CallerIF = nullptr;
2616 TargetTransformInfo &TTI = GetTTI(*Caller);
2617 bool CallerIsFMV = TTI.isMultiversionedFunction(*Caller);
2618 // The caller is a version of a known IFunc.
2619 if (auto It = VersionOf.find(Caller); It != VersionOf.end())
2620 CallerIF = It->second;
2621 else if (!CallerIsFMV && OptimizeNonFMVCallers) {
2622 // The caller is non-FMV.
2623 auto [It, Inserted] = FeatureMask.try_emplace(Caller);
2624 if (Inserted)
2625 It->second = TTI.getFeatureMask(*Caller);
2626 } else
2627 // The caller is none of the above, skip.
2628 continue;
2629 auto [It, Inserted] = CallSites.try_emplace(Caller);
2630 if (Inserted) {
2631 if (CallerIsFMV)
2632 CallerIFuncs.insert(CallerIF);
2633 else
2634 NonFMVCallers.push_back(Caller);
2635 }
2636 It->second.push_back(CB);
2637 }
2638 }
2639 }
2640
2641 if (CallSites.empty())
2642 continue;
2643
2644 LLVM_DEBUG(dbgs() << "Statically resolving calls to function "
2645 << CalleeIF->getResolverFunction()->getName() << "\n");
2646
2647 // The complexity of this algorithm is linear: O(NumCallers + NumCallees)
2648 // if NumCallers > MaxIFuncVersions || NumCallees > MaxIFuncVersions,
2649 // otherwise it is cubic: O((NumCallers ^ 2) x NumCallees).
2650 auto staticallyResolveCalls = [&](ArrayRef<Function *> Callers,
2651 ArrayRef<Function *> Callees,
2652 bool CallerIsFMV) {
2653 bool AllowExpensiveChecks = CallerIsFMV &&
2654 Callers.size() <= MaxIFuncVersions &&
2655 Callees.size() <= MaxIFuncVersions;
2656 // Index to the highest callee candidate.
2657 unsigned J = 0;
2658
2659 for (unsigned I = 0, E = Callers.size(); I < E; ++I) {
2660 // There are no callee candidates left.
2661 if (J == Callees.size())
2662 break;
2663
2664 Function *Caller = Callers[I];
2665 APInt CallerBits = FeatureMask[Caller];
2666
2667 // Compare the feature bits of the best callee candidate with all the
2668 // caller versions preceeding the current one. For each prior caller
2669 // discard feature bits that are known to be available in the current
2670 // caller. As long as the known missing feature bits are a subset of the
2671 // callee feature bits, advance to the next callee and start over.
2672 auto eliminateAvailableFeatures = [&](unsigned BestCandidate) {
2673 unsigned K = 0;
2674 while (K < I && BestCandidate < Callees.size()) {
2675 APInt MissingBits = FeatureMask[Callers[K]] & ~CallerBits;
2676 if (MissingBits.isSubsetOf(FeatureMask[Callees[BestCandidate]])) {
2677 ++BestCandidate;
2678 // Start over.
2679 K = 0;
2680 } else
2681 ++K;
2682 }
2683 return BestCandidate;
2684 };
2685
2686 unsigned BestCandidate =
2687 AllowExpensiveChecks ? eliminateAvailableFeatures(J) : J;
2688 // No callee candidate was found for this caller.
2689 if (BestCandidate == Callees.size())
2690 continue;
2691
2692 LLVM_DEBUG(dbgs() << " Examining "
2693 << (CallerIsFMV ? "FMV" : "regular") << " caller "
2694 << Caller->getName() << "\n");
2695
2696 Function *Callee = Callees[BestCandidate];
2697 APInt CalleeBits = FeatureMask[Callee];
2698
2699 // Statically resolve calls from the current caller to the current
2700 // callee, iff the caller feature bits are a superset of the callee
2701 // feature bits.
2702 if (CalleeBits.isSubsetOf(CallerBits)) {
2703 // Not all caller versions are necessarily users of the callee IFUNC.
2704 if (auto It = CallSites.find(Caller); It != CallSites.end()) {
2705 for (CallBase *CS : It->second) {
2706 LLVM_DEBUG(dbgs() << " Redirecting call " << Caller->getName()
2707 << " -> " << Callee->getName() << "\n");
2708 CS->setCalledOperand(Callee);
2709 }
2710 Changed = true;
2711 }
2712 }
2713
2714 // Nothing else to do about non-FMV callers.
2715 if (!CallerIsFMV)
2716 continue;
2717
2718 // For FMV callers, as long as the caller feature bits are a subset of
2719 // the callee feature bits, advance to the next callee. This effectively
2720 // prevents considering the current callee as a candidate for static
2721 // resolution by following callers.
2722 while (CallerBits.isSubsetOf(FeatureMask[Callees[J]]) &&
2723 ++J < Callees.size())
2724 ;
2725 }
2726 };
2727
2728 auto &Callees = VersionedFuncs[CalleeIF];
2729
2730 // Optimize non-FMV calls.
2732 staticallyResolveCalls(NonFMVCallers, Callees, /*CallerIsFMV=*/false);
2733
2734 // Optimize FMV calls.
2735 for (GlobalIFunc *CallerIF : CallerIFuncs) {
2736 auto &Callers = VersionedFuncs[CallerIF];
2737 staticallyResolveCalls(Callers, Callees, /*CallerIsFMV=*/true);
2738 }
2739
2740 if (CalleeIF->use_empty() ||
2741 all_of(CalleeIF->users(), [](User *U) { return isa<GlobalAlias>(U); }))
2742 NumIFuncsResolved++;
2743 }
2744 return Changed;
2745}
2746
2747static bool
2752 function_ref<DominatorTree &(Function &)> LookupDomTree,
2753 function_ref<void(Function &F)> ChangedCFGCallback,
2754 function_ref<void(Function &F)> DeleteFnCallback) {
2755 SmallPtrSet<const Comdat *, 8> NotDiscardableComdats;
2756 bool Changed = false;
2757 bool LocalChange = true;
2758 std::optional<uint32_t> FirstNotFullyEvaluatedPriority;
2759
2760 while (LocalChange) {
2761 LocalChange = false;
2762
2763 NotDiscardableComdats.clear();
2764 for (const GlobalVariable &GV : M.globals())
2765 if (const Comdat *C = GV.getComdat())
2766 if (!GV.isDiscardableIfUnused() || !GV.use_empty())
2767 NotDiscardableComdats.insert(C);
2768 for (Function &F : M)
2769 if (const Comdat *C = F.getComdat())
2770 if (!F.isDefTriviallyDead())
2771 NotDiscardableComdats.insert(C);
2772 for (GlobalAlias &GA : M.aliases())
2773 if (const Comdat *C = GA.getComdat())
2774 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
2775 NotDiscardableComdats.insert(C);
2776
2777 // Delete functions that are trivially dead, ccc -> fastcc
2778 LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree,
2779 NotDiscardableComdats, ChangedCFGCallback,
2780 DeleteFnCallback);
2781
2782 // Optimize global_ctors list.
2783 LocalChange |=
2784 optimizeGlobalCtorsList(M, [&](uint32_t Priority, Function *F) {
2785 if (FirstNotFullyEvaluatedPriority &&
2786 *FirstNotFullyEvaluatedPriority != Priority)
2787 return false;
2788 bool Evaluated = EvaluateStaticConstructor(F, DL, &GetTLI(*F));
2789 if (!Evaluated)
2790 FirstNotFullyEvaluatedPriority = Priority;
2791 return Evaluated;
2792 });
2793
2794 // Optimize non-address-taken globals.
2795 LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree,
2796 NotDiscardableComdats);
2797
2798 // Resolve aliases, when possible.
2799 LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats);
2800
2801 // Try to remove trivial global destructors if they are not removed
2802 // already.
2803 if (Function *CXAAtExitFn =
2804 FindAtExitLibFunc(M, GetTLI, LibFunc_cxa_atexit))
2805 LocalChange |= OptimizeEmptyGlobalAtExitDtors(CXAAtExitFn, true);
2806
2807 if (Function *AtExitFn = FindAtExitLibFunc(M, GetTLI, LibFunc_atexit))
2808 LocalChange |= OptimizeEmptyGlobalAtExitDtors(AtExitFn, false);
2809
2810 // Optimize IFuncs whose callee's are statically known.
2811 LocalChange |= OptimizeStaticIFuncs(M);
2812
2813 // Optimize IFuncs based on the target features of the caller.
2814 LocalChange |= OptimizeNonTrivialIFuncs(M, GetTTI);
2815
2816 // Remove any IFuncs that are now dead.
2817 LocalChange |= DeleteDeadIFuncs(M, NotDiscardableComdats);
2818
2819 Changed |= LocalChange;
2820 }
2821
2822 // TODO: Move all global ctors functions to the end of the module for code
2823 // layout.
2824
2825 return Changed;
2826}
2827
2829 auto &DL = M.getDataLayout();
2830 auto &FAM =
2832 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{
2833 return FAM.getResult<DominatorTreeAnalysis>(F);
2834 };
2835 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2836 return FAM.getResult<TargetLibraryAnalysis>(F);
2837 };
2838 auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
2839 return FAM.getResult<TargetIRAnalysis>(F);
2840 };
2841
2842 auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
2843 return FAM.getResult<BlockFrequencyAnalysis>(F);
2844 };
2845 auto ChangedCFGCallback = [&FAM](Function &F) {
2846 FAM.invalidate(F, PreservedAnalyses::none());
2847 };
2848 auto DeleteFnCallback = [&FAM](Function &F) { FAM.clear(F, F.getName()); };
2849
2850 if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree,
2851 ChangedCFGCallback, DeleteFnCallback))
2852 return PreservedAnalyses::all();
2853
2855 // We made sure to clear analyses for deleted functions.
2857 // The only place we modify the CFG is when calling
2858 // removeUnreachableBlocks(), but there we make sure to invalidate analyses
2859 // for modified functions.
2861 return PA;
2862}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
#define DEBUG_TYPE
static bool IsSafeComputationToRemove(Value *V, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Given a value that is stored to a global but never read, determine whether it's safe to remove the st...
static Function * FindAtExitLibFunc(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, LibFunc Func)
static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
static Function * hasSideeffectFreeStaticResolution(GlobalIFunc &IF)
static bool tryToOptimizeStoreOfAllocationToGlobal(GlobalVariable *GV, CallInst *CI, const DataLayout &DL, TargetLibraryInfo *TLI)
If we have a global that is only initialized with a fixed size allocation try to transform the progra...
static void ConstantPropUsersOf(Value *V, const DataLayout &DL, TargetLibraryInfo *TLI)
Walk the use list of V, constant folding all of the instructions that are foldable.
static bool OptimizeStaticIFuncs(Module &M)
Find IFuncs that have resolvers that always point at the same statically known callee,...
static bool hasOnlyColdCalls(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, ChangeableCCCacheTy &ChangeableCCCache)
static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV)
Return true if all uses of any loads from GV will trap if the loaded value is null.
static bool hasChangeableCCImpl(Function *F)
Return true if this is a calling convention that we'd like to change.
static bool AllUsesOfValueWillTrapIfNull(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs)
Return true if all users of the specified value will trap if the value is dynamically null.
static GlobalVariable * OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI, uint64_t AllocSize, Constant *InitVal, const DataLayout &DL, TargetLibraryInfo *TLI)
This function takes the specified global variable, and transforms the program as if it always contain...
static bool collectVersions(Value *V, SmallVectorImpl< Function * > &Versions, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool IsEmptyAtExitFunction(const Function &Fn)
Returns whether the given function is an empty C++ destructor or atexit handler and can therefore be ...
static bool collectSRATypes(DenseMap< uint64_t, GlobalPart > &Parts, GlobalVariable *GV, const DataLayout &DL)
Look at all uses of the global and determine which (offset, type) pairs it can be split into.
static bool valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI, const GlobalVariable *GV)
Scan the use-list of GV checking to make sure that there are no complex uses of GV.
static bool OptimizeFunctions(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool DeleteDeadIFuncs(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static void RemoveAttribute(Function *F, Attribute::AttrKind A)
static bool hasChangeableCC(Function *F, ChangeableCCCacheTy &ChangeableCCCache)
static bool deleteIfDead(GlobalValue &GV, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats, function_ref< void(Function &)> DeleteFnCallback=nullptr)
static void RemovePreallocated(Function *F)
static cl::opt< bool > OptimizeNonFMVCallers("optimize-non-fmv-callers", cl::desc("Statically resolve calls to versioned " "functions from non-versioned callers."), cl::init(true), cl::Hidden)
static bool processGlobal(GlobalValue &GV, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI)
Return true if the block containing the call site has a BlockFrequency of less than ColdCCRelFreq% of...
static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, uint64_t FragmentOffsetInBits, uint64_t FragmentSizeInBits, uint64_t VarSize)
Copy over the debug info for a variable to its SRA replacements.
static cl::opt< bool > EnableColdCCStressTest("enable-coldcc-stress-test", cl::desc("Enable stress test of coldcc by adding " "calling conv to all internal functions."), cl::init(false), cl::Hidden)
static bool OptimizeGlobalAliases(Module &M, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
At this point, we have learned that the only two values ever stored into GV are its initializer and O...
static void ChangeCalleesToFastCall(Function *F)
Walk all of the direct calls of the specified function, changing them to FastCC.
static bool hasMustTailCallers(Function *F)
static bool OptimizeNonTrivialIFuncs(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool OptimizeGlobalVars(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree, SmallPtrSetImpl< const Comdat * > &NotDiscardableComdats)
static void allUsesOfLoadAndStores(GlobalVariable *GV, SmallVector< Value *, 4 > &Uses)
Get all the loads/store uses for global variable GV.
static bool OptimizeEmptyGlobalAtExitDtors(Function *CXAAtExitFn, bool isCXX)
static bool mayHaveOtherReferences(GlobalValue &GV, const LLVMUsed &U)
static void changeCallSitesToColdCC(Function *F)
static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, Attribute::AttrKind A)
static bool hasInvokeCallers(Function *F)
static bool OptimizeAwayTrappingUsesOfValue(Instruction *V, Constant *NewV)
static void setUsedInitializer(GlobalVariable &V, const SmallPtrSetImpl< GlobalValue * > &Init)
static cl::opt< unsigned > MaxIFuncVersions("max-ifunc-versions", cl::Hidden, cl::init(5), cl::desc("Maximum number of caller/callee versions that is allowed for " "using the expensive (cubic) static resolution algorithm."))
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
The specified global has only one non-null value stored into it.
static bool isValidCandidateForColdCC(Function &F, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, const std::vector< Function * > &AllCallsCold)
static cl::opt< int > ColdCCRelFreq("coldcc-rel-freq", cl::Hidden, cl::init(2), cl::desc("Maximum block frequency, expressed as a percentage of caller's " "entry frequency, for a call site to be considered cold for enabling " "coldcc"))
static bool optimizeGlobalsInModule(Module &M, const DataLayout &DL, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI, function_ref< DominatorTree &(Function &)> LookupDomTree, function_ref< void(Function &F)> ChangedCFGCallback, function_ref< void(Function &F)> DeleteFnCallback)
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, TargetLibraryInfo *TLI)
Evaluate static constructors in the function, if we can.
static bool CleanupConstantGlobalUsers(GlobalVariable *GV, const DataLayout &DL)
We just marked GV constant.
SmallDenseMap< Function *, bool, 8 > ChangeableCCCacheTy
static bool isLeakCheckerRoot(GlobalVariable *GV)
Is this global variable possibly used by a leak checker as a root?
static bool forwardStoredOnceStore(GlobalVariable *GV, const StoreInst *StoredOnceStore, function_ref< DominatorTree &(Function &)> LookupDomTree)
static int compareNames(Constant *const *A, Constant *const *B)
static bool CleanupPointerRootUsers(GlobalVariable *GV, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
This GV is a pointer root.
static bool isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV, function_ref< DominatorTree &(Function &)> LookupDomTree)
static bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, function_ref< TargetTransformInfo &(Function &)> GetTTI, function_ref< TargetLibraryInfo &(Function &)> GetTLI, function_ref< DominatorTree &(Function &)> LookupDomTree)
Analyze the specified global variable and optimize it if possible.
static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, bool &RenameTarget)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
Perform scalar replacement of aggregates on the specified global variable.
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
void setCalledOperand(Value *V)
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isMustTailCall() const
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1470
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
const Constant * stripPointerCasts() const
Definition Constant.h:233
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DWARF expression.
LLVM_ABI bool extractIfOffset(int64_t &Offset) const
If this is a constant offset, extract it.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
A pair of DIGlobalVariable and DIExpression.
uint64_t getSizeInBits() const
Base class for variables.
DIType * getType() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
bool erase(const KeyT &Val)
Definition DenseMap.h:377
unsigned size() const
Definition DenseMap.h:172
bool empty() const
Definition DenseMap.h:171
iterator begin()
Definition DenseMap.h:137
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
Definition Evaluator.h:37
DenseMap< GlobalVariable *, Constant * > getMutatedInitializers() const
Definition Evaluator.h:102
LLVM_ABI bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant * > &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it.
const SmallPtrSetImpl< GlobalVariable * > & getInvariants() const
Definition Evaluator.h:109
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
const Function & getFunction() const
Definition Function.h:167
iterator begin()
Definition Function.h:838
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:759
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:274
ThreadLocalMode getThreadLocalMode() const
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
bool hasGlobalUnnamedAddr() const
UnnamedAddr getUnnamedAddr() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
bool isExternallyInitialized() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition Globals.cpp:647
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
LLVMContext & getContext() const
Definition Metadata.h:1233
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void insertGlobalVariable(GlobalVariable *GV)
Insert global variable GV at the end of the global variable list and take ownership.
Definition Module.h:657
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:339
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2213
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
int compare(StringRef RHS) const
Compare two strings; the result is negative, zero, or positive if this string is lexicographically le...
Definition StringRef.h:177
Class to represent struct types.
ArrayRef< Type * > elements() const
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ StructTyID
Structures.
Definition Type.h:75
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ PointerTyID
Pointers.
Definition Type.h:74
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI void set(Value *Val)
Definition Value.h:874
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Use * op_iterator
Definition User.h:254
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
use_iterator use_begin()
Definition Value.h:364
User * user_back()
Definition Value.h:412
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
user_iterator_impl< User > user_iterator
Definition Value.h:391
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ X86_ThisCall
Similar to X86_StdCall.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
bool used(const UsedT *U, size_t I)
Definition DenseMap.h:72
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
@ Dead
Unused definition.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
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:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2912
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1558
LLVM_ABI bool optimizeGlobalCtorsList(Module &M, function_ref< bool(uint32_t, Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
TargetTransformInfo TTI
DWARFExpression::Operation Op
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
Definition Local.cpp:537
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1596
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:932
Part of the global at a specific offset, which is only accessed through loads and stores with the giv...
Constant * Initializer
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
As we analyze each global or thread-local variable, keep track of some information about it.
@ InitializerStored
This global is stored to, but the only thing stored is the constant it was initialized with.
@ StoredOnce
This global is stored to, but only its initializer and one other value is ever stored to it.
static LLVM_ABI bool analyzeGlobal(const Value *V, GlobalStatus &GS)
Look at all uses of the global and fill in the GlobalStatus structure.
Various options to control the behavior of getObjectSize.
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439