xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SafeStack.cpp (revision cab6a39d7b343596a5823e65c0f7b426551ec22d)
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 
17 #include "SafeStackLayout.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/InlineCost.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/StackLifetime.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/ConstantRange.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DIBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Use.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/Transforms/Utils/Cloning.h"
66 #include "llvm/Transforms/Utils/Local.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <string>
71 #include <utility>
72 
73 using namespace llvm;
74 using namespace llvm::safestack;
75 
76 #define DEBUG_TYPE "safe-stack"
77 
78 namespace llvm {
79 
80 STATISTIC(NumFunctions, "Total number of functions");
81 STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
82 STATISTIC(NumUnsafeStackRestorePointsFunctions,
83           "Number of functions that use setjmp or exceptions");
84 
85 STATISTIC(NumAllocas, "Total number of allocas");
86 STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
87 STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
88 STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
89 STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
90 
91 } // namespace llvm
92 
93 /// Use __safestack_pointer_address even if the platform has a faster way of
94 /// access safe stack pointer.
95 static cl::opt<bool>
96     SafeStackUsePointerAddress("safestack-use-pointer-address",
97                                   cl::init(false), cl::Hidden);
98 
99 // Disabled by default due to PR32143.
100 static cl::opt<bool> ClColoring("safe-stack-coloring",
101                                 cl::desc("enable safe stack coloring"),
102                                 cl::Hidden, cl::init(false));
103 
104 namespace {
105 
106 /// Rewrite an SCEV expression for a memory access address to an expression that
107 /// represents offset from the given alloca.
108 ///
109 /// The implementation simply replaces all mentions of the alloca with zero.
110 class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
111   const Value *AllocaPtr;
112 
113 public:
114   AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
115       : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
116 
117   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
118     if (Expr->getValue() == AllocaPtr)
119       return SE.getZero(Expr->getType());
120     return Expr;
121   }
122 };
123 
124 /// The SafeStack pass splits the stack of each function into the safe
125 /// stack, which is only accessed through memory safe dereferences (as
126 /// determined statically), and the unsafe stack, which contains all
127 /// local variables that are accessed in ways that we can't prove to
128 /// be safe.
129 class SafeStack {
130   Function &F;
131   const TargetLoweringBase &TL;
132   const DataLayout &DL;
133   ScalarEvolution &SE;
134 
135   Type *StackPtrTy;
136   Type *IntPtrTy;
137   Type *Int32Ty;
138   Type *Int8Ty;
139 
140   Value *UnsafeStackPtr = nullptr;
141 
142   /// Unsafe stack alignment. Each stack frame must ensure that the stack is
143   /// aligned to this value. We need to re-align the unsafe stack if the
144   /// alignment of any object on the stack exceeds this value.
145   ///
146   /// 16 seems like a reasonable upper bound on the alignment of objects that we
147   /// might expect to appear on the stack on most common targets.
148   enum { StackAlignment = 16 };
149 
150   /// Return the value of the stack canary.
151   Value *getStackGuard(IRBuilder<> &IRB, Function &F);
152 
153   /// Load stack guard from the frame and check if it has changed.
154   void checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
155                        AllocaInst *StackGuardSlot, Value *StackGuard);
156 
157   /// Find all static allocas, dynamic allocas, return instructions and
158   /// stack restore points (exception unwind blocks and setjmp calls) in the
159   /// given function and append them to the respective vectors.
160   void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
161                  SmallVectorImpl<AllocaInst *> &DynamicAllocas,
162                  SmallVectorImpl<Argument *> &ByValArguments,
163                  SmallVectorImpl<Instruction *> &Returns,
164                  SmallVectorImpl<Instruction *> &StackRestorePoints);
165 
166   /// Calculate the allocation size of a given alloca. Returns 0 if the
167   /// size can not be statically determined.
168   uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
169 
170   /// Allocate space for all static allocas in \p StaticAllocas,
171   /// replace allocas with pointers into the unsafe stack.
172   ///
173   /// \returns A pointer to the top of the unsafe stack after all unsafe static
174   /// allocas are allocated.
175   Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
176                                         ArrayRef<AllocaInst *> StaticAllocas,
177                                         ArrayRef<Argument *> ByValArguments,
178                                         Instruction *BasePointer,
179                                         AllocaInst *StackGuardSlot);
180 
181   /// Generate code to restore the stack after all stack restore points
182   /// in \p StackRestorePoints.
183   ///
184   /// \returns A local variable in which to maintain the dynamic top of the
185   /// unsafe stack if needed.
186   AllocaInst *
187   createStackRestorePoints(IRBuilder<> &IRB, Function &F,
188                            ArrayRef<Instruction *> StackRestorePoints,
189                            Value *StaticTop, bool NeedDynamicTop);
190 
191   /// Replace all allocas in \p DynamicAllocas with code to allocate
192   /// space dynamically on the unsafe stack and store the dynamic unsafe stack
193   /// top to \p DynamicTop if non-null.
194   void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
195                                        AllocaInst *DynamicTop,
196                                        ArrayRef<AllocaInst *> DynamicAllocas);
197 
198   bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
199 
200   bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
201                           const Value *AllocaPtr, uint64_t AllocaSize);
202   bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
203                     uint64_t AllocaSize);
204 
205   bool ShouldInlinePointerAddress(CallInst &CI);
206   void TryInlinePointerAddress();
207 
208 public:
209   SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
210             ScalarEvolution &SE)
211       : F(F), TL(TL), DL(DL), SE(SE),
212         StackPtrTy(Type::getInt8PtrTy(F.getContext())),
213         IntPtrTy(DL.getIntPtrType(F.getContext())),
214         Int32Ty(Type::getInt32Ty(F.getContext())),
215         Int8Ty(Type::getInt8Ty(F.getContext())) {}
216 
217   // Run the transformation on the associated function.
218   // Returns whether the function was changed.
219   bool run();
220 };
221 
222 uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
223   uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
224   if (AI->isArrayAllocation()) {
225     auto C = dyn_cast<ConstantInt>(AI->getArraySize());
226     if (!C)
227       return 0;
228     Size *= C->getZExtValue();
229   }
230   return Size;
231 }
232 
233 bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
234                              const Value *AllocaPtr, uint64_t AllocaSize) {
235   AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
236   const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
237 
238   uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
239   ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
240   ConstantRange SizeRange =
241       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
242   ConstantRange AccessRange = AccessStartRange.add(SizeRange);
243   ConstantRange AllocaRange =
244       ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
245   bool Safe = AllocaRange.contains(AccessRange);
246 
247   LLVM_DEBUG(
248       dbgs() << "[SafeStack] "
249              << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
250              << *AllocaPtr << "\n"
251              << "            Access " << *Addr << "\n"
252              << "            SCEV " << *Expr
253              << " U: " << SE.getUnsignedRange(Expr)
254              << ", S: " << SE.getSignedRange(Expr) << "\n"
255              << "            Range " << AccessRange << "\n"
256              << "            AllocaRange " << AllocaRange << "\n"
257              << "            " << (Safe ? "safe" : "unsafe") << "\n");
258 
259   return Safe;
260 }
261 
262 bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
263                                    const Value *AllocaPtr,
264                                    uint64_t AllocaSize) {
265   if (auto MTI = dyn_cast<MemTransferInst>(MI)) {
266     if (MTI->getRawSource() != U && MTI->getRawDest() != U)
267       return true;
268   } else {
269     if (MI->getRawDest() != U)
270       return true;
271   }
272 
273   const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
274   // Non-constant size => unsafe. FIXME: try SCEV getRange.
275   if (!Len) return false;
276   return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
277 }
278 
279 /// Check whether a given allocation must be put on the safe
280 /// stack or not. The function analyzes all uses of AI and checks whether it is
281 /// only accessed in a memory safe way (as decided statically).
282 bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
283   // Go through all uses of this alloca and check whether all accesses to the
284   // allocated object are statically known to be memory safe and, hence, the
285   // object can be placed on the safe stack.
286   SmallPtrSet<const Value *, 16> Visited;
287   SmallVector<const Value *, 8> WorkList;
288   WorkList.push_back(AllocaPtr);
289 
290   // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
291   while (!WorkList.empty()) {
292     const Value *V = WorkList.pop_back_val();
293     for (const Use &UI : V->uses()) {
294       auto I = cast<const Instruction>(UI.getUser());
295       assert(V == UI.get());
296 
297       switch (I->getOpcode()) {
298       case Instruction::Load:
299         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
300                           AllocaSize))
301           return false;
302         break;
303 
304       case Instruction::VAArg:
305         // "va-arg" from a pointer is safe.
306         break;
307       case Instruction::Store:
308         if (V == I->getOperand(0)) {
309           // Stored the pointer - conservatively assume it may be unsafe.
310           LLVM_DEBUG(dbgs()
311                      << "[SafeStack] Unsafe alloca: " << *AllocaPtr
312                      << "\n            store of address: " << *I << "\n");
313           return false;
314         }
315 
316         if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
317                           AllocaPtr, AllocaSize))
318           return false;
319         break;
320 
321       case Instruction::Ret:
322         // Information leak.
323         return false;
324 
325       case Instruction::Call:
326       case Instruction::Invoke: {
327         const CallBase &CS = *cast<CallBase>(I);
328 
329         if (I->isLifetimeStartOrEnd())
330           continue;
331 
332         if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
333           if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
334             LLVM_DEBUG(dbgs()
335                        << "[SafeStack] Unsafe alloca: " << *AllocaPtr
336                        << "\n            unsafe memintrinsic: " << *I << "\n");
337             return false;
338           }
339           continue;
340         }
341 
342         // LLVM 'nocapture' attribute is only set for arguments whose address
343         // is not stored, passed around, or used in any other non-trivial way.
344         // We assume that passing a pointer to an object as a 'nocapture
345         // readnone' argument is safe.
346         // FIXME: a more precise solution would require an interprocedural
347         // analysis here, which would look at all uses of an argument inside
348         // the function being called.
349         auto B = CS.arg_begin(), E = CS.arg_end();
350         for (auto A = B; A != E; ++A)
351           if (A->get() == V)
352             if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
353                                                CS.doesNotAccessMemory()))) {
354               LLVM_DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
355                                 << "\n            unsafe call: " << *I << "\n");
356               return false;
357             }
358         continue;
359       }
360 
361       default:
362         if (Visited.insert(I).second)
363           WorkList.push_back(cast<const Instruction>(I));
364       }
365     }
366   }
367 
368   // All uses of the alloca are safe, we can place it on the safe stack.
369   return true;
370 }
371 
372 Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
373   Value *StackGuardVar = TL.getIRStackGuard(IRB);
374   if (!StackGuardVar)
375     StackGuardVar =
376         F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
377   return IRB.CreateLoad(StackPtrTy, StackGuardVar, "StackGuard");
378 }
379 
380 void SafeStack::findInsts(Function &F,
381                           SmallVectorImpl<AllocaInst *> &StaticAllocas,
382                           SmallVectorImpl<AllocaInst *> &DynamicAllocas,
383                           SmallVectorImpl<Argument *> &ByValArguments,
384                           SmallVectorImpl<Instruction *> &Returns,
385                           SmallVectorImpl<Instruction *> &StackRestorePoints) {
386   for (Instruction &I : instructions(&F)) {
387     if (auto AI = dyn_cast<AllocaInst>(&I)) {
388       ++NumAllocas;
389 
390       uint64_t Size = getStaticAllocaAllocationSize(AI);
391       if (IsSafeStackAlloca(AI, Size))
392         continue;
393 
394       if (AI->isStaticAlloca()) {
395         ++NumUnsafeStaticAllocas;
396         StaticAllocas.push_back(AI);
397       } else {
398         ++NumUnsafeDynamicAllocas;
399         DynamicAllocas.push_back(AI);
400       }
401     } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
402       if (CallInst *CI = I.getParent()->getTerminatingMustTailCall())
403         Returns.push_back(CI);
404       else
405         Returns.push_back(RI);
406     } else if (auto CI = dyn_cast<CallInst>(&I)) {
407       // setjmps require stack restore.
408       if (CI->getCalledFunction() && CI->canReturnTwice())
409         StackRestorePoints.push_back(CI);
410     } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
411       // Exception landing pads require stack restore.
412       StackRestorePoints.push_back(LP);
413     } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
414       if (II->getIntrinsicID() == Intrinsic::gcroot)
415         report_fatal_error(
416             "gcroot intrinsic not compatible with safestack attribute");
417     }
418   }
419   for (Argument &Arg : F.args()) {
420     if (!Arg.hasByValAttr())
421       continue;
422     uint64_t Size =
423         DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
424     if (IsSafeStackAlloca(&Arg, Size))
425       continue;
426 
427     ++NumUnsafeByValArguments;
428     ByValArguments.push_back(&Arg);
429   }
430 }
431 
432 AllocaInst *
433 SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
434                                     ArrayRef<Instruction *> StackRestorePoints,
435                                     Value *StaticTop, bool NeedDynamicTop) {
436   assert(StaticTop && "The stack top isn't set.");
437 
438   if (StackRestorePoints.empty())
439     return nullptr;
440 
441   // We need the current value of the shadow stack pointer to restore
442   // after longjmp or exception catching.
443 
444   // FIXME: On some platforms this could be handled by the longjmp/exception
445   // runtime itself.
446 
447   AllocaInst *DynamicTop = nullptr;
448   if (NeedDynamicTop) {
449     // If we also have dynamic alloca's, the stack pointer value changes
450     // throughout the function. For now we store it in an alloca.
451     DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
452                                   "unsafe_stack_dynamic_ptr");
453     IRB.CreateStore(StaticTop, DynamicTop);
454   }
455 
456   // Restore current stack pointer after longjmp/exception catch.
457   for (Instruction *I : StackRestorePoints) {
458     ++NumUnsafeStackRestorePoints;
459 
460     IRB.SetInsertPoint(I->getNextNode());
461     Value *CurrentTop =
462         DynamicTop ? IRB.CreateLoad(StackPtrTy, DynamicTop) : StaticTop;
463     IRB.CreateStore(CurrentTop, UnsafeStackPtr);
464   }
465 
466   return DynamicTop;
467 }
468 
469 void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, Instruction &RI,
470                                 AllocaInst *StackGuardSlot, Value *StackGuard) {
471   Value *V = IRB.CreateLoad(StackPtrTy, StackGuardSlot);
472   Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
473 
474   auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
475   auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
476   MDNode *Weights = MDBuilder(F.getContext())
477                         .createBranchWeights(SuccessProb.getNumerator(),
478                                              FailureProb.getNumerator());
479   Instruction *CheckTerm =
480       SplitBlockAndInsertIfThen(Cmp, &RI,
481                                 /* Unreachable */ true, Weights);
482   IRBuilder<> IRBFail(CheckTerm);
483   // FIXME: respect -fsanitize-trap / -ftrap-function here?
484   FunctionCallee StackChkFail =
485       F.getParent()->getOrInsertFunction("__stack_chk_fail", IRB.getVoidTy());
486   IRBFail.CreateCall(StackChkFail, {});
487 }
488 
489 /// We explicitly compute and set the unsafe stack layout for all unsafe
490 /// static alloca instructions. We save the unsafe "base pointer" in the
491 /// prologue into a local variable and restore it in the epilogue.
492 Value *SafeStack::moveStaticAllocasToUnsafeStack(
493     IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
494     ArrayRef<Argument *> ByValArguments, Instruction *BasePointer,
495     AllocaInst *StackGuardSlot) {
496   if (StaticAllocas.empty() && ByValArguments.empty())
497     return BasePointer;
498 
499   DIBuilder DIB(*F.getParent());
500 
501   StackLifetime SSC(F, StaticAllocas, StackLifetime::LivenessType::May);
502   static const StackLifetime::LiveRange NoColoringRange(1, true);
503   if (ClColoring)
504     SSC.run();
505 
506   for (auto *I : SSC.getMarkers()) {
507     auto *Op = dyn_cast<Instruction>(I->getOperand(1));
508     const_cast<IntrinsicInst *>(I)->eraseFromParent();
509     // Remove the operand bitcast, too, if it has no more uses left.
510     if (Op && Op->use_empty())
511       Op->eraseFromParent();
512   }
513 
514   // Unsafe stack always grows down.
515   StackLayout SSL(StackAlignment);
516   if (StackGuardSlot) {
517     Type *Ty = StackGuardSlot->getAllocatedType();
518     unsigned Align =
519         std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
520     SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
521                   Align, SSC.getFullLiveRange());
522   }
523 
524   for (Argument *Arg : ByValArguments) {
525     Type *Ty = Arg->getType()->getPointerElementType();
526     uint64_t Size = DL.getTypeStoreSize(Ty);
527     if (Size == 0)
528       Size = 1; // Don't create zero-sized stack objects.
529 
530     // Ensure the object is properly aligned.
531     unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
532                               Arg->getParamAlignment());
533     SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
534   }
535 
536   for (AllocaInst *AI : StaticAllocas) {
537     Type *Ty = AI->getAllocatedType();
538     uint64_t Size = getStaticAllocaAllocationSize(AI);
539     if (Size == 0)
540       Size = 1; // Don't create zero-sized stack objects.
541 
542     // Ensure the object is properly aligned.
543     unsigned Align =
544         std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
545 
546     SSL.addObject(AI, Size, Align,
547                   ClColoring ? SSC.getLiveRange(AI) : NoColoringRange);
548   }
549 
550   SSL.computeLayout();
551   unsigned FrameAlignment = SSL.getFrameAlignment();
552 
553   // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
554   // (AlignmentSkew).
555   if (FrameAlignment > StackAlignment) {
556     // Re-align the base pointer according to the max requested alignment.
557     assert(isPowerOf2_32(FrameAlignment));
558     IRB.SetInsertPoint(BasePointer->getNextNode());
559     BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
560         IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
561                       ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
562         StackPtrTy));
563   }
564 
565   IRB.SetInsertPoint(BasePointer->getNextNode());
566 
567   if (StackGuardSlot) {
568     unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
569     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
570                                ConstantInt::get(Int32Ty, -Offset));
571     Value *NewAI =
572         IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
573 
574     // Replace alloc with the new location.
575     StackGuardSlot->replaceAllUsesWith(NewAI);
576     StackGuardSlot->eraseFromParent();
577   }
578 
579   for (Argument *Arg : ByValArguments) {
580     unsigned Offset = SSL.getObjectOffset(Arg);
581     MaybeAlign Align(SSL.getObjectAlignment(Arg));
582     Type *Ty = Arg->getType()->getPointerElementType();
583 
584     uint64_t Size = DL.getTypeStoreSize(Ty);
585     if (Size == 0)
586       Size = 1; // Don't create zero-sized stack objects.
587 
588     Value *Off = IRB.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
589                                ConstantInt::get(Int32Ty, -Offset));
590     Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
591                                      Arg->getName() + ".unsafe-byval");
592 
593     // Replace alloc with the new location.
594     replaceDbgDeclare(Arg, BasePointer, DIB, DIExpression::ApplyOffset,
595                       -Offset);
596     Arg->replaceAllUsesWith(NewArg);
597     IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
598     IRB.CreateMemCpy(Off, Align, Arg, Arg->getParamAlign(), Size);
599   }
600 
601   // Allocate space for every unsafe static AllocaInst on the unsafe stack.
602   for (AllocaInst *AI : StaticAllocas) {
603     IRB.SetInsertPoint(AI);
604     unsigned Offset = SSL.getObjectOffset(AI);
605 
606     replaceDbgDeclare(AI, BasePointer, DIB, DIExpression::ApplyOffset, -Offset);
607     replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
608 
609     // Replace uses of the alloca with the new location.
610     // Insert address calculation close to each use to work around PR27844.
611     std::string Name = std::string(AI->getName()) + ".unsafe";
612     while (!AI->use_empty()) {
613       Use &U = *AI->use_begin();
614       Instruction *User = cast<Instruction>(U.getUser());
615 
616       Instruction *InsertBefore;
617       if (auto *PHI = dyn_cast<PHINode>(User))
618         InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
619       else
620         InsertBefore = User;
621 
622       IRBuilder<> IRBUser(InsertBefore);
623       Value *Off = IRBUser.CreateGEP(Int8Ty, BasePointer, // BasePointer is i8*
624                                      ConstantInt::get(Int32Ty, -Offset));
625       Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
626 
627       if (auto *PHI = dyn_cast<PHINode>(User))
628         // PHI nodes may have multiple incoming edges from the same BB (why??),
629         // all must be updated at once with the same incoming value.
630         PHI->setIncomingValueForBlock(PHI->getIncomingBlock(U), Replacement);
631       else
632         U.set(Replacement);
633     }
634 
635     AI->eraseFromParent();
636   }
637 
638   // Re-align BasePointer so that our callees would see it aligned as
639   // expected.
640   // FIXME: no need to update BasePointer in leaf functions.
641   unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
642 
643   // Update shadow stack pointer in the function epilogue.
644   IRB.SetInsertPoint(BasePointer->getNextNode());
645 
646   Value *StaticTop =
647       IRB.CreateGEP(Int8Ty, BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
648                     "unsafe_stack_static_top");
649   IRB.CreateStore(StaticTop, UnsafeStackPtr);
650   return StaticTop;
651 }
652 
653 void SafeStack::moveDynamicAllocasToUnsafeStack(
654     Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
655     ArrayRef<AllocaInst *> DynamicAllocas) {
656   DIBuilder DIB(*F.getParent());
657 
658   for (AllocaInst *AI : DynamicAllocas) {
659     IRBuilder<> IRB(AI);
660 
661     // Compute the new SP value (after AI).
662     Value *ArraySize = AI->getArraySize();
663     if (ArraySize->getType() != IntPtrTy)
664       ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
665 
666     Type *Ty = AI->getAllocatedType();
667     uint64_t TySize = DL.getTypeAllocSize(Ty);
668     Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
669 
670     Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(StackPtrTy, UnsafeStackPtr),
671                                    IntPtrTy);
672     SP = IRB.CreateSub(SP, Size);
673 
674     // Align the SP value to satisfy the AllocaInst, type and stack alignments.
675     unsigned Align = std::max(
676         std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
677         (unsigned)StackAlignment);
678 
679     assert(isPowerOf2_32(Align));
680     Value *NewTop = IRB.CreateIntToPtr(
681         IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
682         StackPtrTy);
683 
684     // Save the stack pointer.
685     IRB.CreateStore(NewTop, UnsafeStackPtr);
686     if (DynamicTop)
687       IRB.CreateStore(NewTop, DynamicTop);
688 
689     Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
690     if (AI->hasName() && isa<Instruction>(NewAI))
691       NewAI->takeName(AI);
692 
693     replaceDbgDeclare(AI, NewAI, DIB, DIExpression::ApplyOffset, 0);
694     AI->replaceAllUsesWith(NewAI);
695     AI->eraseFromParent();
696   }
697 
698   if (!DynamicAllocas.empty()) {
699     // Now go through the instructions again, replacing stacksave/stackrestore.
700     for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
701       Instruction *I = &*(It++);
702       auto II = dyn_cast<IntrinsicInst>(I);
703       if (!II)
704         continue;
705 
706       if (II->getIntrinsicID() == Intrinsic::stacksave) {
707         IRBuilder<> IRB(II);
708         Instruction *LI = IRB.CreateLoad(StackPtrTy, UnsafeStackPtr);
709         LI->takeName(II);
710         II->replaceAllUsesWith(LI);
711         II->eraseFromParent();
712       } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
713         IRBuilder<> IRB(II);
714         Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
715         SI->takeName(II);
716         assert(II->use_empty());
717         II->eraseFromParent();
718       }
719     }
720   }
721 }
722 
723 bool SafeStack::ShouldInlinePointerAddress(CallInst &CI) {
724   Function *Callee = CI.getCalledFunction();
725   if (CI.hasFnAttr(Attribute::AlwaysInline) &&
726       isInlineViable(*Callee).isSuccess())
727     return true;
728   if (Callee->isInterposable() || Callee->hasFnAttribute(Attribute::NoInline) ||
729       CI.isNoInline())
730     return false;
731   return true;
732 }
733 
734 void SafeStack::TryInlinePointerAddress() {
735   auto *CI = dyn_cast<CallInst>(UnsafeStackPtr);
736   if (!CI)
737     return;
738 
739   if(F.hasOptNone())
740     return;
741 
742   Function *Callee = CI->getCalledFunction();
743   if (!Callee || Callee->isDeclaration())
744     return;
745 
746   if (!ShouldInlinePointerAddress(*CI))
747     return;
748 
749   InlineFunctionInfo IFI;
750   InlineFunction(*CI, IFI);
751 }
752 
753 bool SafeStack::run() {
754   assert(F.hasFnAttribute(Attribute::SafeStack) &&
755          "Can't run SafeStack on a function without the attribute");
756   assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
757 
758   ++NumFunctions;
759 
760   SmallVector<AllocaInst *, 16> StaticAllocas;
761   SmallVector<AllocaInst *, 4> DynamicAllocas;
762   SmallVector<Argument *, 4> ByValArguments;
763   SmallVector<Instruction *, 4> Returns;
764 
765   // Collect all points where stack gets unwound and needs to be restored
766   // This is only necessary because the runtime (setjmp and unwind code) is
767   // not aware of the unsafe stack and won't unwind/restore it properly.
768   // To work around this problem without changing the runtime, we insert
769   // instrumentation to restore the unsafe stack pointer when necessary.
770   SmallVector<Instruction *, 4> StackRestorePoints;
771 
772   // Find all static and dynamic alloca instructions that must be moved to the
773   // unsafe stack, all return instructions and stack restore points.
774   findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
775             StackRestorePoints);
776 
777   if (StaticAllocas.empty() && DynamicAllocas.empty() &&
778       ByValArguments.empty() && StackRestorePoints.empty())
779     return false; // Nothing to do in this function.
780 
781   if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
782       !ByValArguments.empty())
783     ++NumUnsafeStackFunctions; // This function has the unsafe stack.
784 
785   if (!StackRestorePoints.empty())
786     ++NumUnsafeStackRestorePointsFunctions;
787 
788   IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
789   // Calls must always have a debug location, or else inlining breaks. So
790   // we explicitly set a artificial debug location here.
791   if (DISubprogram *SP = F.getSubprogram())
792     IRB.SetCurrentDebugLocation(
793         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP));
794   if (SafeStackUsePointerAddress) {
795     FunctionCallee Fn = F.getParent()->getOrInsertFunction(
796         "__safestack_pointer_address", StackPtrTy->getPointerTo(0));
797     UnsafeStackPtr = IRB.CreateCall(Fn);
798   } else {
799     UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
800   }
801 
802   // Load the current stack pointer (we'll also use it as a base pointer).
803   // FIXME: use a dedicated register for it ?
804   Instruction *BasePointer =
805       IRB.CreateLoad(StackPtrTy, UnsafeStackPtr, false, "unsafe_stack_ptr");
806   assert(BasePointer->getType() == StackPtrTy);
807 
808   AllocaInst *StackGuardSlot = nullptr;
809   // FIXME: implement weaker forms of stack protector.
810   if (F.hasFnAttribute(Attribute::StackProtect) ||
811       F.hasFnAttribute(Attribute::StackProtectStrong) ||
812       F.hasFnAttribute(Attribute::StackProtectReq)) {
813     Value *StackGuard = getStackGuard(IRB, F);
814     StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
815     IRB.CreateStore(StackGuard, StackGuardSlot);
816 
817     for (Instruction *RI : Returns) {
818       IRBuilder<> IRBRet(RI);
819       checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
820     }
821   }
822 
823   // The top of the unsafe stack after all unsafe static allocas are
824   // allocated.
825   Value *StaticTop = moveStaticAllocasToUnsafeStack(
826       IRB, F, StaticAllocas, ByValArguments, BasePointer, StackGuardSlot);
827 
828   // Safe stack object that stores the current unsafe stack top. It is updated
829   // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
830   // This is only needed if we need to restore stack pointer after longjmp
831   // or exceptions, and we have dynamic allocations.
832   // FIXME: a better alternative might be to store the unsafe stack pointer
833   // before setjmp / invoke instructions.
834   AllocaInst *DynamicTop = createStackRestorePoints(
835       IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
836 
837   // Handle dynamic allocas.
838   moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
839                                   DynamicAllocas);
840 
841   // Restore the unsafe stack pointer before each return.
842   for (Instruction *RI : Returns) {
843     IRB.SetInsertPoint(RI);
844     IRB.CreateStore(BasePointer, UnsafeStackPtr);
845   }
846 
847   TryInlinePointerAddress();
848 
849   LLVM_DEBUG(dbgs() << "[SafeStack]     safestack applied\n");
850   return true;
851 }
852 
853 class SafeStackLegacyPass : public FunctionPass {
854   const TargetMachine *TM = nullptr;
855 
856 public:
857   static char ID; // Pass identification, replacement for typeid..
858 
859   SafeStackLegacyPass() : FunctionPass(ID) {
860     initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
861   }
862 
863   void getAnalysisUsage(AnalysisUsage &AU) const override {
864     AU.addRequired<TargetPassConfig>();
865     AU.addRequired<TargetLibraryInfoWrapperPass>();
866     AU.addRequired<AssumptionCacheTracker>();
867   }
868 
869   bool runOnFunction(Function &F) override {
870     LLVM_DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
871 
872     if (!F.hasFnAttribute(Attribute::SafeStack)) {
873       LLVM_DEBUG(dbgs() << "[SafeStack]     safestack is not requested"
874                            " for this function\n");
875       return false;
876     }
877 
878     if (F.isDeclaration()) {
879       LLVM_DEBUG(dbgs() << "[SafeStack]     function definition"
880                            " is not available\n");
881       return false;
882     }
883 
884     TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
885     auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
886     if (!TL)
887       report_fatal_error("TargetLowering instance is required");
888 
889     auto *DL = &F.getParent()->getDataLayout();
890     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
891     auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
892 
893     // Compute DT and LI only for functions that have the attribute.
894     // This is only useful because the legacy pass manager doesn't let us
895     // compute analyzes lazily.
896     // In the backend pipeline, nothing preserves DT before SafeStack, so we
897     // would otherwise always compute it wastefully, even if there is no
898     // function with the safestack attribute.
899     DominatorTree DT(F);
900     LoopInfo LI(DT);
901 
902     ScalarEvolution SE(F, TLI, ACT, DT, LI);
903 
904     return SafeStack(F, *TL, *DL, SE).run();
905   }
906 };
907 
908 } // end anonymous namespace
909 
910 char SafeStackLegacyPass::ID = 0;
911 
912 INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, DEBUG_TYPE,
913                       "Safe Stack instrumentation pass", false, false)
914 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
915 INITIALIZE_PASS_END(SafeStackLegacyPass, DEBUG_TYPE,
916                     "Safe Stack instrumentation pass", false, false)
917 
918 FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }
919