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