LLVM 24.0.0git
SafeStack.cpp
Go to the documentation of this file.
1//===- SafeStack.cpp - Safe Stack Insertion -------------------------------===//
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 splits the stack into the safe stack (kept as-is for LLVM backend)
10// and the unsafe stack (explicitly allocated and managed through the runtime
11// support library).
12//
13// http://clang.llvm.org/docs/SafeStack.html
14//
15//===----------------------------------------------------------------------===//
16
18#include "CodeGenOptions.h"
19#include "SafeStackLayout.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/Statistic.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DIBuilder.h"
42#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Dominators.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/Instruction.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/MDBuilder.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
55#include "llvm/IR/Type.h"
56#include "llvm/IR/Use.h"
57#include "llvm/IR/Value.h"
59#include "llvm/Pass.h"
61#include "llvm/Support/Debug.h"
68#include <algorithm>
69#include <cassert>
70#include <cstdint>
71#include <optional>
72#include <string>
73
74using namespace llvm;
75using namespace llvm::safestack;
76
77#define DEBUG_TYPE "safe-stack"
78
79STATISTIC(NumFunctions, "Total number of functions");
80STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
81STATISTIC(NumUnsafeStackRestorePointsFunctions,
82 "Number of functions that use setjmp or exceptions");
83
84STATISTIC(NumAllocas, "Total number of allocas");
85STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
86STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
87STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
88STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
89
90namespace {
91
92/// The SafeStack pass splits the stack of each function into the safe
93/// stack, which is only accessed through memory safe dereferences (as
94/// determined statically), and the unsafe stack, which contains all
95/// local variables that are accessed in ways that we can't prove to
96/// be safe.
97class SafeStack {
98 const CodeGenOptions &Opts;
99 Function &F;
100 const TargetLoweringBase &TL;
101 const LibcallLoweringInfo &Libcalls;
102 const DataLayout &DL;
103 DomTreeUpdater *DTU;
104 ScalarEvolution &SE;
105
106 Type *StackPtrTy;
107 Type *AddrTy;
108
109 Value *UnsafeStackPtr = nullptr;
110
111 /// Unsafe stack alignment. Each stack frame must ensure that the stack is
112 /// aligned to this value. We need to re-align the unsafe stack if the
113 /// alignment of any object on the stack exceeds this value.
114 ///
115 /// 16 seems like a reasonable upper bound on the alignment of objects that we
116 /// might expect to appear on the stack on most common targets.
117 static constexpr Align StackAlignment = Align::Constant<16>();
118
119 /// Return the value of the stack canary.
121
122 /// Load stack guard from the frame and check if it has changed.
123 void checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
124 AllocaInst *StackGuardSlot, Value *StackGuard);
125
126 /// Find all static allocas, dynamic allocas, return instructions and
127 /// stack restore points (exception unwind blocks and setjmp calls) in the
128 /// given function and append them to the respective vectors.
129 void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
130 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
131 SmallVectorImpl<Argument *> &ByValArguments,
133 SmallVectorImpl<Instruction *> &StackRestorePoints);
134
135 /// Calculate the allocation size of a given alloca. Returns 0 if the
136 /// size can not be statically determined.
137 uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
138
139 /// Allocate space for all static allocas in \p StaticAllocas,
140 /// replace allocas with pointers into the unsafe stack.
141 ///
142 /// \returns A pointer to the top of the unsafe stack after all unsafe static
143 /// allocas are allocated.
144 Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
145 ArrayRef<AllocaInst *> StaticAllocas,
146 ArrayRef<Argument *> ByValArguments,
147 Instruction *BasePointer,
148 AllocaInst *StackGuardSlot);
149
150 /// Generate code to restore the stack after all stack restore points
151 /// in \p StackRestorePoints.
152 ///
153 /// \returns A local variable in which to maintain the dynamic top of the
154 /// unsafe stack if needed.
155 AllocaInst *
156 createStackRestorePoints(IRBuilder<> &IRB, Function &F,
157 ArrayRef<Instruction *> StackRestorePoints,
158 Value *StaticTop, bool NeedDynamicTop);
159
160 /// Replace all allocas in \p DynamicAllocas with code to allocate
161 /// space dynamically on the unsafe stack and store the dynamic unsafe stack
162 /// top to \p DynamicTop if non-null.
163 void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
164 AllocaInst *DynamicTop,
165 ArrayRef<AllocaInst *> DynamicAllocas);
166
167 bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
168
169 bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
170 const Value *AllocaPtr, uint64_t AllocaSize);
171 bool IsAccessSafe(Value *Addr, TypeSize Size, const Value *AllocaPtr,
172 uint64_t AllocaSize);
173 bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
174 uint64_t AllocaSize);
175
176 bool ShouldInlinePointerAddress(CallInst &CI);
177 void TryInlinePointerAddress();
178
179public:
180 SafeStack(Function &F, const TargetLoweringBase &TL,
181 const LibcallLoweringInfo &Libcalls, const DataLayout &DL,
183 : Opts(getCodeGenOptions(F)), F(F), TL(TL), Libcalls(Libcalls), DL(DL),
184 DTU(DTU), SE(SE), StackPtrTy(DL.getAllocaPtrType(F.getContext())),
185 AddrTy(DL.getAddressType(StackPtrTy)) {}
186
187 // Run the transformation on the associated function.
188 // Returns whether the function was changed.
189 bool run();
190};
191
192uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
193 if (auto Size = AI->getAllocationSize(DL))
194 if (Size->isFixed())
195 return Size->getFixedValue();
196 return 0;
197}
198
199bool SafeStack::IsAccessSafe(Value *Addr, TypeSize AccessSize,
200 const Value *AllocaPtr, uint64_t AllocaSize) {
201 if (AccessSize.isScalable()) {
202 // In case we don't know the size at compile time we cannot verify if the
203 // access is safe.
204 return false;
205 }
206 return IsAccessSafe(Addr, AccessSize.getFixedValue(), AllocaPtr, AllocaSize);
207}
208
209bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
210 const Value *AllocaPtr, uint64_t AllocaSize) {
211 const SCEV *AddrExpr = SE.getSCEV(Addr);
212 const auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(AddrExpr));
213 if (!Base || Base->getValue() != AllocaPtr) {
215 dbgs() << "[SafeStack] "
216 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
217 << *AllocaPtr << "\n"
218 << "SCEV " << *AddrExpr << " not directly based on alloca\n");
219 return false;
220 }
221
222 const SCEV *Expr = SE.removePointerBase(AddrExpr);
224 ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
225 ConstantRange SizeRange =
226 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
227 ConstantRange AccessRange = AccessStartRange.add(SizeRange);
228 ConstantRange AllocaRange =
229 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
230 bool Safe = AllocaRange.contains(AccessRange);
231
233 dbgs() << "[SafeStack] "
234 << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
235 << *AllocaPtr << "\n"
236 << " Access " << *Addr << "\n"
237 << " SCEV " << *Expr
238 << " U: " << SE.getUnsignedRange(Expr)
239 << ", S: " << SE.getSignedRange(Expr) << "\n"
240 << " Range " << AccessRange << "\n"
241 << " AllocaRange " << AllocaRange << "\n"
242 << " " << (Safe ? "safe" : "unsafe") << "\n");
243
244 return Safe;
245}
246
247bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
248 const Value *AllocaPtr,
249 uint64_t AllocaSize) {
250 if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
251 if (MTI->getRawSource() != U && MTI->getRawDest() != U)
252 return true;
253 } else {
254 if (MI->getRawDest() != U)
255 return true;
256 }
257
258 auto Len = MI->getLengthInBytes();
259 // Non-constant size => unsafe. FIXME: try SCEV getRange.
260 if (!Len) return false;
261 return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
262}
263
264/// Check whether a given allocation must be put on the safe
265/// stack or not. The function analyzes all uses of AI and checks whether it is
266/// only accessed in a memory safe way (as decided statically).
267bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
268 // Go through all uses of this alloca and check whether all accesses to the
269 // allocated object are statically known to be memory safe and, hence, the
270 // object can be placed on the safe stack.
271 SmallPtrSet<const Value *, 16> Visited;
272 SmallVector<const Value *, 8> WorkList;
273 WorkList.push_back(AllocaPtr);
274
275 // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
276 while (!WorkList.empty()) {
277 const Value *V = WorkList.pop_back_val();
278 for (const Use &UI : V->uses()) {
279 auto I = cast<const Instruction>(UI.getUser());
280 assert(V == UI.get());
281
282 switch (I->getOpcode()) {
283 case Instruction::Load:
284 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
285 AllocaSize))
286 return false;
287 break;
288
289 case Instruction::VAArg:
290 // "va-arg" from a pointer is safe.
291 break;
292 case Instruction::Store:
293 if (V == I->getOperand(0)) {
294 // Stored the pointer - conservatively assume it may be unsafe.
296 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
297 << "\n store of address: " << *I << "\n");
298 return false;
299 }
300
301 if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
302 AllocaPtr, AllocaSize))
303 return false;
304 break;
305
306 case Instruction::Ret:
307 // Information leak.
308 return false;
309
310 case Instruction::Call:
311 case Instruction::Invoke: {
312 const CallBase &CS = *cast<CallBase>(I);
313
314 if (I->isLifetimeStartOrEnd())
315 continue;
316
317 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
318 if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
320 << "[SafeStack] Unsafe alloca: " << *AllocaPtr
321 << "\n unsafe memintrinsic: " << *I << "\n");
322 return false;
323 }
324 continue;
325 }
326
327 // LLVM 'nocapture' attribute is only set for arguments whose address
328 // is not stored, passed around, or used in any other non-trivial way.
329 // We assume that passing a pointer to an object as a 'nocapture
330 // readnone' argument is safe.
331 // FIXME: a more precise solution would require an interprocedural
332 // analysis here, which would look at all uses of an argument inside
333 // the function being called.
334 auto B = CS.arg_begin(), E = CS.arg_end();
335 for (const auto *A = B; A != E; ++A)
336 if (A->get() == V)
337 if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
338 CS.doesNotAccessMemory()))) {
339 LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
340 << "\n unsafe call: " << *I << "\n");
341 return false;
342 }
343 continue;
344 }
345
346 default:
347 if (Visited.insert(I).second)
349 }
350 }
351 }
352
353 // All uses of the alloca are safe, we can place it on the safe stack.
354 return true;
355}
356
357Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
358 Value *StackGuardVar = TL.getIRStackGuard(IRB, Libcalls);
359 Module *M = F.getParent();
360
361 if (!StackGuardVar) {
362 TL.insertSSPDeclarations(*M, Libcalls);
363 return IRB.CreateIntrinsic(Intrinsic::stackguard, {});
364 }
365
366 return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
367}
368
369void SafeStack::findInsts(Function &F,
370 SmallVectorImpl<AllocaInst *> &StaticAllocas,
371 SmallVectorImpl<AllocaInst *> &DynamicAllocas,
372 SmallVectorImpl<Argument *> &ByValArguments,
373 SmallVectorImpl<Instruction *> &Returns,
374 SmallVectorImpl<Instruction *> &StackRestorePoints) {
375 for (Instruction &I : instructions(&F)) {
376 if (auto AI = dyn_cast<AllocaInst>(&I)) {
377 ++NumAllocas;
378
379 uint64_t Size = getStaticAllocaAllocationSize(AI);
380 if (IsSafeStackAlloca(AI, Size))
381 continue;
382
383 if (AI->isStaticAlloca()) {
384 ++NumUnsafeStaticAllocas;
385 StaticAllocas.push_back(AI);
386 } else {
387 ++NumUnsafeDynamicAllocas;
388 DynamicAllocas.push_back(AI);
389 }
390 } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
391 if (CallInst *CI = I.getParent()->getTerminatingMustTailCall())
392 Returns.push_back(CI);
393 else
394 Returns.push_back(RI);
395 } else if (auto CI = dyn_cast<CallInst>(&I)) {
396 // setjmps require stack restore.
397 if (CI->getCalledFunction() && CI->canReturnTwice())
398 StackRestorePoints.push_back(CI);
399 } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
400 // Exception landing pads require stack restore.
401 StackRestorePoints.push_back(LP);
402 } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
403 if (II->getIntrinsicID() == Intrinsic::gcroot)
405 "gcroot intrinsic not compatible with safestack attribute");
406 }
407 }
408 for (Argument &Arg : F.args()) {
409 if (!Arg.hasByValAttr())
410 continue;
411 uint64_t Size = DL.getTypeStoreSize(Arg.getParamByValType());
412 if (IsSafeStackAlloca(&Arg, Size))
413 continue;
414
415 ++NumUnsafeByValArguments;
416 ByValArguments.push_back(&Arg);
417 }
418}
419
420AllocaInst *
421SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
422 ArrayRef<Instruction *> StackRestorePoints,
423 Value *StaticTop, bool NeedDynamicTop) {
424 assert(StaticTop && "The stack top isn't set.");
425
426 if (StackRestorePoints.empty())
427 return nullptr;
428
429 // We need the current value of the shadow stack pointer to restore
430 // after longjmp or exception catching.
431
432 // FIXME: On some platforms this could be handled by the longjmp/exception
433 // runtime itself.
434
435 AllocaInst *DynamicTop = nullptr;
436 if (NeedDynamicTop) {
437 // If we also have dynamic alloca's, the stack pointer value changes
438 // throughout the function. For now we store it in an alloca.
439 DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
440 "unsafe_stack_dynamic_ptr");
441 IRB.CreateStore(StaticTop, DynamicTop);
442 }
443
444 // Restore current stack pointer after longjmp/exception catch.
445 for (Instruction *I : StackRestorePoints) {
446 ++NumUnsafeStackRestorePoints;
447
448 IRB.SetInsertPoint(I->getNextNode());
449 Value *CurrentTop =
450 DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
451 IRB.CreateStore(CurrentTop, UnsafeStackPtr);
452 }
453
454 return DynamicTop;
455}
456
457void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
458 AllocaInst *StackGuardSlot, Value *StackGuard) {
459 Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
460 Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
461
464 MDNode *Weights = MDBuilder(F.getContext())
465 .createBranchWeights(SuccessProb.getNumerator(),
466 FailureProb.getNumerator());
467 Instruction *CheckTerm =
468 SplitBlockAndInsertIfThen(Cmp, &RI, /* Unreachable */ true, Weights, DTU);
469 IRBuilder<> IRBFail(CheckTerm);
470 // FIXME: respect -fsanitize-trap / -ftrap-function here?
471 RTLIB::LibcallImpl StackChkFailImpl =
472 Libcalls.getLibcallImpl(RTLIB::STACKPROTECTOR_CHECK_FAIL);
473 if (StackChkFailImpl == RTLIB::Unsupported) {
474 F.getContext().emitError(
475 "no libcall available for stackprotector check fail");
476 return;
477 }
478
479 FunctionCallee StackChkFail =
481 *F.getParent(), StackChkFailImpl);
482 CallInst *Call = IRBFail.CreateCall(StackChkFail, {});
483 Call->setCallingConv(Libcalls.getLibcallImplCallingConv(StackChkFailImpl));
484}
485
486/// We explicitly compute and set the unsafe stack layout for all unsafe
487/// static alloca instructions. We save the unsafe "base pointer" in the
488/// prologue into a local variable and restore it in the epilogue.
489Value *SafeStack::moveStaticAllocasToUnsafeStack(
490 IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
491 ArrayRef<Argument *> ByValArguments, Instruction *BasePointer,
492 AllocaInst *StackGuardSlot) {
493 if (StaticAllocas.empty() && ByValArguments.empty())
494 return BasePointer;
495
496 DIBuilder DIB(*F.getParent());
497
498 StackLifetime SSC(F, StaticAllocas, StackLifetime::LivenessType::May);
499 static const StackLifetime::LiveRange NoColoringRange(1, true);
500 if (Opts.safe_stack_coloring)
501 SSC.run();
502
503 for (const auto *I : SSC.getMarkers()) {
504 auto *Op = dyn_cast<Instruction>(I->getOperand(1));
505 const_cast<IntrinsicInst *>(I)->eraseFromParent();
506 // Remove the operand bitcast, too, if it has no more uses left.
507 if (Op && Op->use_empty())
508 Op->eraseFromParent();
509 }
510
511 // Unsafe stack always grows down.
512 StackLayout SSL(Opts, StackAlignment);
513 if (StackGuardSlot) {
514 SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
515 StackGuardSlot->getAlign(), SSC.getFullLiveRange());
516 }
517
518 for (Argument *Arg : ByValArguments) {
519 Type *Ty = Arg->getParamByValType();
520 uint64_t Size = DL.getTypeStoreSize(Ty);
521 if (Size == 0)
522 Size = 1; // Don't create zero-sized stack objects.
523
524 // Ensure the object is properly aligned.
525 Align Align = DL.getPrefTypeAlign(Ty);
526 if (auto A = Arg->getParamAlign())
527 Align = std::max(Align, *A);
528 SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
529 }
530
531 for (AllocaInst *AI : StaticAllocas) {
532 uint64_t Size = getStaticAllocaAllocationSize(AI);
533 if (Size == 0)
534 Size = 1; // Don't create zero-sized stack objects.
535
536 SSL.addObject(AI, Size, AI->getAlign(),
537 Opts.safe_stack_coloring ? SSC.getLiveRange(AI)
538 : NoColoringRange);
539 }
540
541 SSL.computeLayout();
542 Align FrameAlignment = SSL.getFrameAlignment();
543
544 // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
545 // (AlignmentSkew).
546 if (FrameAlignment > StackAlignment) {
547 // Re-align the base pointer according to the max requested alignment.
548 IRB.SetInsertPoint(BasePointer->getNextNode());
549 BasePointer = IRB.CreateIntrinsicWithoutFolding(
550 StackPtrTy, Intrinsic::ptrmask,
551 {BasePointer, ConstantInt::get(AddrTy, ~(FrameAlignment.value() - 1))});
552 }
553
554 IRB.SetInsertPoint(BasePointer->getNextNode());
555
556 if (StackGuardSlot) {
557 unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
558 Value *Off =
559 IRB.CreatePtrAddWithSignedOffset(BasePointer, -(int64_t)Offset);
560 Value *NewAI =
561 IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
562
563 // Replace alloc with the new location.
564 StackGuardSlot->replaceAllUsesWith(NewAI);
565 StackGuardSlot->eraseFromParent();
566 }
567
568 for (Argument *Arg : ByValArguments) {
569 unsigned Offset = SSL.getObjectOffset(Arg);
570 MaybeAlign Align(SSL.getObjectAlignment(Arg));
571 Type *Ty = Arg->getParamByValType();
572
573 uint64_t Size = DL.getTypeStoreSize(Ty);
574 if (Size == 0)
575 Size = 1; // Don't create zero-sized stack objects.
576
577 Value *Off =
578 IRB.CreatePtrAddWithSignedOffset(BasePointer, -(int64_t)Offset);
579 Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
580 Arg->getName() + ".unsafe-byval");
581
582 // Replace alloc with the new location.
583 replaceDbgDeclare(Arg, BasePointer, DIB, DIExpression::ApplyOffset,
584 -Offset);
585 Arg->replaceAllUsesWith(NewArg);
587 IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlign(), Size);
588 }
589
590 // Allocate space for every unsafe static AllocaInst on the unsafe stack.
591 for (AllocaInst *AI : StaticAllocas) {
592 IRB.SetInsertPoint(AI);
593 unsigned Offset = SSL.getObjectOffset(AI);
594
595 replaceDbgDeclare(AI, BasePointer, DIB, DIExpression::ApplyOffset, -Offset);
596 replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
597
598 // Replace uses of the alloca with the new location.
599 // Insert address calculation close to each use to work around PR27844.
600 std::string Name = std::string(AI->getName()) + ".unsafe";
601 while (!AI->use_empty()) {
602 Use &U = *AI->use_begin();
603 Instruction *User = cast<Instruction>(U.getUser());
604
605 // Drop lifetime markers now that this is no longer an alloca.
606 // SafeStack has already performed its own stack coloring.
607 if (User->isLifetimeStartOrEnd()) {
608 User->eraseFromParent();
609 continue;
610 }
611
612 Instruction *InsertBefore;
613 if (auto *PHI = dyn_cast<PHINode>(User))
614 InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
615 else
616 InsertBefore = User;
617
618 IRBuilder<> IRBUser(InsertBefore);
619 Value *Off =
620 IRBUser.CreatePtrAddWithSignedOffset(BasePointer, -(int64_t)Offset);
621 Value *Replacement =
622 IRBUser.CreateAddrSpaceCast(Off, AI->getType(), Name);
623
624 if (auto *PHI = dyn_cast<PHINode>(User))
625 // PHI nodes may have multiple incoming edges from the same BB (why??),
626 // all must be updated at once with the same incoming value.
627 PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
628 else
629 U.set(Replacement);
630 }
631
632 AI->eraseFromParent();
633 }
634
635 // Re-align BasePointer so that our callees would see it aligned as
636 // expected.
637 // FIXME: no need to update BasePointer in leaf functions.
638 unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
639
640 F.addFnAttr("unsafe-stack-size", utostr(FrameSize));
641
642 // Update shadow stack pointer in the function epilogue.
643 IRB.SetInsertPoint(BasePointer->getNextNode());
644
645 Value *StaticTop = IRB.CreatePtrAddWithSignedOffset(
646 BasePointer, -(int64_t)FrameSize, "unsafe_stack_static_top");
647 IRB.CreateStore(StaticTop, UnsafeStackPtr);
648 return StaticTop;
649}
650
651void SafeStack::moveDynamicAllocasToUnsafeStack(
652 Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
653 ArrayRef<AllocaInst *> DynamicAllocas) {
654 DIBuilder DIB(*F.getParent());
655
656 for (AllocaInst *AI : DynamicAllocas) {
657 IRBuilder<> IRB(AI);
658
659 // Compute the new SP value (after AI).
660 Value *Size = IRB.CreateAllocationSize(AddrTy, AI);
661 Value *SP = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
662 SP = IRB.CreatePtrAdd(SP, IRB.CreateNeg(Size));
663
664 // Align the SP value to satisfy the AllocaInst and stack alignments.
665 auto Align = std::max(AI->getAlign(), StackAlignment);
666
667 Value *NewTop = IRB.CreateIntrinsic(
668 StackPtrTy, Intrinsic::ptrmask,
669 {SP, ConstantInt::getSigned(AddrTy, ~uint64_t(Align.value() - 1))});
670
671 // Save the stack pointer.
672 IRB.CreateStore(NewTop, UnsafeStackPtr);
673 if (DynamicTop)
674 IRB.CreateStore(NewTop, DynamicTop);
675
676 Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
677 if (AI->hasName() && isa<Instruction>(NewAI))
678 NewAI->takeName(AI);
679
681 AI->replaceAllUsesWith(NewAI);
682 AI->eraseFromParent();
683 }
684
685 if (!DynamicAllocas.empty()) {
686 // Now go through the instructions again, replacing stacksave/stackrestore.
687 for (Instruction &I : llvm::make_early_inc_range(instructions(&F))) {
688 auto *II = dyn_cast<IntrinsicInst>(&I);
689 if (!II)
690 continue;
691
692 if (II->getIntrinsicID() == Intrinsic::stacksave) {
693 IRBuilder<> IRB(II);
694 Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
695 LI->takeName(II);
696 II->replaceAllUsesWith(LI);
697 II->eraseFromParent();
698 } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
699 IRBuilder<> IRB(II);
700 Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
701 SI->takeName(II);
702 assert(II->use_empty());
703 II->eraseFromParent();
704 }
705 }
706 }
707}
708
709bool SafeStack::ShouldInlinePointerAddress(CallInst &CI) {
711 if (CI.hasFnAttr(Attribute::AlwaysInline) &&
712 isInlineViable(*Callee).isSuccess())
713 return true;
714 if (Callee->isInterposable() || CI.isNoInline())
715 return false;
716 return true;
717}
718
719void SafeStack::TryInlinePointerAddress() {
720 auto *CI = dyn_cast<CallInst>(UnsafeStackPtr);
721 if (!CI)
722 return;
723
724 if(F.hasOptNone())
725 return;
726
728 if (!Callee || Callee->isDeclaration())
729 return;
730
731 if (!ShouldInlinePointerAddress(*CI))
732 return;
733
734 // InlineFunction can modify the callers CFG, but it has no DomTreeUpdater
735 // hook. Since SafeStack preserves the DominatorTree, we must rebuild it
736 // after a successful inline instead of leaving the cached tree stale.
737 InlineFunctionInfo IFI;
738 if (InlineFunction(*CI, IFI).isSuccess() && DTU)
739 DTU->recalculate(F);
740}
741
742bool SafeStack::run() {
743 assert(F.hasFnAttribute(Attribute::SafeStack) &&
744 "Can't run SafeStack on a function without the attribute");
745 assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
746
747 ++NumFunctions;
748
749 SmallVector<AllocaInst *, 16> StaticAllocas;
750 SmallVector<AllocaInst *, 4> DynamicAllocas;
751 SmallVector<Argument *, 4> ByValArguments;
752 SmallVector<Instruction *, 4> Returns;
753
754 // Collect all points where stack gets unwound and needs to be restored
755 // This is only necessary because the runtime (setjmp and unwind code) is
756 // not aware of the unsafe stack and won't unwind/restore it properly.
757 // To work around this problem without changing the runtime, we insert
758 // instrumentation to restore the unsafe stack pointer when necessary.
759 SmallVector<Instruction *, 4> StackRestorePoints;
760
761 // Find all static and dynamic alloca instructions that must be moved to the
762 // unsafe stack, all return instructions and stack restore points.
763 findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
764 StackRestorePoints);
765
766 if (StaticAllocas.empty() && DynamicAllocas.empty() &&
767 ByValArguments.empty() && StackRestorePoints.empty())
768 return false; // Nothing to do in this function.
769
770 if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
771 !ByValArguments.empty())
772 ++NumUnsafeStackFunctions; // This function has the unsafe stack.
773
774 if (!StackRestorePoints.empty())
775 ++NumUnsafeStackRestorePointsFunctions;
776
777 IRBuilder<> IRB(F.begin()->getFirstInsertionPt());
779 // Calls must always have a debug location, or else inlining breaks. So
780 // we explicitly set a artificial debug location here.
781 if (DISubprogram *SP = F.getSubprogram())
783 DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP));
784 if (Opts.safe_stack_use_pointer_address)
785 UnsafeStackPtr = TL.getSafeStackPointerAddressCall(IRB, Libcalls);
786 else
787 UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB, Libcalls);
788
789 if (!UnsafeStackPtr) {
790 F.getContext().emitError(
791 "no location available for safestack pointer address");
792 UnsafeStackPtr = PoisonValue::get(StackPtrTy);
793 }
794
795 // Load the current stack pointer (we'll also use it as a base pointer).
796 // FIXME: use a dedicated register for it ?
797 Instruction *BasePointer =
798 IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
799 assert(BasePointer->getType() == StackPtrTy);
800
801 AllocaInst *StackGuardSlot = nullptr;
802 // FIXME: implement weaker forms of stack protector.
803 if (F.hasFnAttribute(Attribute::StackProtect) ||
804 F.hasFnAttribute(Attribute::StackProtectStrong) ||
805 F.hasFnAttribute(Attribute::StackProtectReq)) {
806 Value *StackGuard = getStackGuard(IRB, F);
807 StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
808 IRB.CreateStore(StackGuard, StackGuardSlot);
809
810 for (Instruction *RI : Returns) {
811 IRBuilder<> IRBRet(RI);
812 checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
813 }
814 }
815
816 // The top of the unsafe stack after all unsafe static allocas are
817 // allocated.
818 Value *StaticTop = moveStaticAllocasToUnsafeStack(
819 IRB, F, StaticAllocas, ByValArguments, BasePointer, StackGuardSlot);
820
821 // Safe stack object that stores the current unsafe stack top. It is updated
822 // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
823 // This is only needed if we need to restore stack pointer after longjmp
824 // or exceptions, and we have dynamic allocations.
825 // FIXME: a better alternative might be to store the unsafe stack pointer
826 // before setjmp / invoke instructions.
827 AllocaInst *DynamicTop = createStackRestorePoints(
828 IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
829
830 // Handle dynamic allocas.
831 moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
832 DynamicAllocas);
833
834 // Restore the unsafe stack pointer before each return.
835 for (Instruction *RI : Returns) {
836 IRB.SetInsertPoint(RI);
837 IRB.CreateStore(BasePointer, UnsafeStackPtr);
838 }
839
840 TryInlinePointerAddress();
841
842 LLVM_DEBUG(dbgs() << "[SafeStack] safestack applied\n");
843 return true;
844}
845
846class SafeStackLegacyPass : public FunctionPass {
847 const TargetMachine *TM = nullptr;
848
849public:
850 static char ID; // Pass identification, replacement for typeid..
851
852 SafeStackLegacyPass() : FunctionPass(ID) {}
853
854 void getAnalysisUsage(AnalysisUsage &AU) const override {
855 AU.addRequired<LibcallLoweringInfoWrapper>();
856 AU.addRequired<TargetPassConfig>();
857 AU.addRequired<TargetLibraryInfoWrapperPass>();
858 AU.addRequired<AssumptionCacheTracker>();
859 AU.addPreserved<DominatorTreeWrapperPass>();
860 }
861
862 bool runOnFunction(Function &F) override {
863 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
864
865 if (!F.hasFnAttribute(Attribute::SafeStack)) {
866 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
867 " for this function\n");
868 return false;
869 }
870
871 if (F.isDeclaration()) {
872 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
873 " is not available\n");
874 return false;
875 }
876
877 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
878 const TargetSubtargetInfo *Subtarget = TM->getSubtargetImpl(F);
879 auto *TL = Subtarget->getTargetLowering();
880 if (!TL)
881 report_fatal_error("TargetLowering instance is required");
882
883 const LibcallLoweringInfo &Libcalls =
884 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
885 *F.getParent(), *Subtarget);
886
887 auto *DL = &F.getDataLayout();
888 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
889 auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
890
891 // Compute DT and LI only for functions that have the attribute.
892 // This is only useful because the legacy pass manager doesn't let us
893 // compute analyzes lazily.
894
895 DominatorTree *DT;
896 bool ShouldPreserveDominatorTree;
897 std::optional<DominatorTree> LazilyComputedDomTree;
898
899 // Do we already have a DominatorTree available from the previous pass?
900 // Note that we should *NOT* require it, to avoid the case where we end up
901 // not needing it, but the legacy PM would have computed it for us anyways.
902 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
903 DT = &DTWP->getDomTree();
904 ShouldPreserveDominatorTree = true;
905 } else {
906 // Otherwise, we need to compute it.
907 LazilyComputedDomTree.emplace(F);
908 DT = &*LazilyComputedDomTree;
909 ShouldPreserveDominatorTree = false;
910 }
911
912 // Likewise, lazily compute loop info.
913 LoopInfo LI(*DT);
914
915 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
916
917 ScalarEvolution SE(F, TLI, ACT, *DT, LI);
918
919 return SafeStack(F, *TL, Libcalls, *DL,
920 ShouldPreserveDominatorTree ? &DTU : nullptr, SE)
921 .run();
922 }
923};
924
925} // end anonymous namespace
926
929 LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
930
931 if (!F.hasFnAttribute(Attribute::SafeStack)) {
932 LLVM_DEBUG(dbgs() << "[SafeStack] safestack is not requested"
933 " for this function\n");
934 return PreservedAnalyses::all();
935 }
936
937 if (F.isDeclaration()) {
938 LLVM_DEBUG(dbgs() << "[SafeStack] function definition"
939 " is not available\n");
940 return PreservedAnalyses::all();
941 }
942
943 const TargetSubtargetInfo *Subtarget = TM->getSubtargetImpl(F);
944 auto *TL = Subtarget->getTargetLowering();
945
946 auto &DL = F.getDataLayout();
947
948 // preserve DominatorTree
949 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
950 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
951
952 auto &MAMProxy = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
953 const ModuleLibcallLoweringInfo *LibcallLowering =
954 MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(*F.getParent());
955
956 if (!LibcallLowering) {
957 F.getContext().emitError("'" + LibcallLoweringModuleAnalysis::name() +
958 "' analysis required");
959 return PreservedAnalyses::all();
960 }
961
962 const LibcallLoweringInfo &Libcalls =
963 getLibcallLowering(*LibcallLowering, *Subtarget);
964
965 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
966
967 bool Changed = SafeStack(F, *TL, Libcalls, DL, &DTU, SE).run();
968
969 if (!Changed)
970 return PreservedAnalyses::all();
973 return PA;
974}
975
976char SafeStackLegacyPass::ID = 0;
977
979 "Safe Stack instrumentation pass", false, false)
983INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
984 "Safe Stack instrumentation pass", false, false)
985
986FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
VarLocInsertPt getNextNode(const DbgRecord *DVR)
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
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...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static Value * getStackGuard(const TargetLoweringBase &TLI, const LibcallLoweringInfo &Libcalls, Module *M, IRBuilder<> &B, bool *SupportsSelectionDAGSP=nullptr)
Create a stack guard loading and populate whether SelectionDAG SSP is supported.
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 file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
const AArch64TargetLowering * getTargetLowering() const override
an instruction to allocate memory on the stack
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static BranchProbability getBranchProbStackProtector(bool IsLikely)
void setCallingConv(CallingConv::ID CC)
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isNoInline() const
Return true if the call should not be inlined, either because the call site is marked noinline or bec...
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
This class represents a function call, abstracting a target machine's calling convention.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition IRBuilder.h:1886
LLVM_ABI Value * CreateAllocationSize(Type *DestTy, AllocaInst *AI)
Get allocation size of an alloca as a runtime Value* (handles both static and dynamic allocas and vsc...
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
Definition IRBuilder.h:657
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2373
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2462
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition IRBuilder.h:1832
void disableGEPCanonicalization()
Disable canonicalization of getelementptr instructions to ptradd form.
Definition IRBuilder.h:351
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreatePtrAddWithSignedOffset(Value *Ptr, int64_t Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd with a signed constant offset.
Definition IRBuilder.h:2123
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
bool isSuccess() const
Definition InlineCost.h:193
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Tracks which library functions to use for a particular subtarget or function.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This is the common base class for memset/memcpy/memmove.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
Type * getType() const
Return the LLVM type of this SCEV expression.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
Value * getSafeStackPointerAddressCall(IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const
Emits a call to the libcall returning the address of the unsafe stack pointer.
virtual Value * getIRStackGuard(IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const
If the target has a standard location for the stack protector guard, returns the address of that loca...
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
virtual Value * getSafeStackPointerLocation(IRBuilderBase &IRB, const LibcallLoweringInfo &Libcalls) const
Returns the target-specific address of the unsafe stack pointer.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
TargetSubtargetInfo - Generic base class for all target subtargets.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
use_iterator use_begin()
Definition Value.h:366
bool use_empty() const
Definition Value.h:348
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr MCPhysReg SP
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI FunctionPass * createSafeStackPass()
This pass splits the stack into a safe stack and an unsafe stack to protect against stack-based overf...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
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:649
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This function inlines the called function into the basic block of the caller.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI InlineResult isInlineViable(Function &Callee)
Check if it is mechanically possible to inline the function Callee, based on the contents of the func...
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
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
DWARFExpression::Operation Op
LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple dbg.value records when the alloca it describes is replaced with a new value.
Definition Local.cpp:2052
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces dbg.declare record when the address it describes is replaced with a new value.
Definition Local.cpp:2012
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align Constant()
Allow constructions of constexpr Align.
Definition Alignment.h:93
LLVM_ABI FunctionCallee getOrInsertLibcallDecl(Module &M, RTLIB::LibcallImpl LibcallImpl) const