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