xref: /aosp_15_r20/external/swiftshader/third_party/llvm-16.0/llvm/lib/Target/X86/X86KCFI.cpp (revision 03ce13f70fcc45d86ee91b7ee4cab1936a95046e)
1 //===---- X86KCFI.cpp - Implements KCFI -----------------------------------===//
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 file implements KCFI indirect call checking.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86.h"
14 #include "X86InstrInfo.h"
15 #include "X86Subtarget.h"
16 #include "X86TargetMachine.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineInstrBundle.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "x86-kcfi"
26 #define X86_KCFI_PASS_NAME "Insert KCFI indirect call checks"
27 
28 STATISTIC(NumKCFIChecksAdded, "Number of indirect call checks added");
29 
30 namespace {
31 class X86KCFI : public MachineFunctionPass {
32 public:
33   static char ID;
34 
X86KCFI()35   X86KCFI() : MachineFunctionPass(ID) {}
36 
getPassName() const37   StringRef getPassName() const override { return X86_KCFI_PASS_NAME; }
38   bool runOnMachineFunction(MachineFunction &MF) override;
39 
40 private:
41   /// Machine instruction info used throughout the class.
42   const X86InstrInfo *TII = nullptr;
43 
44   /// Emits a KCFI check before an indirect call.
45   /// \returns true if the check was added and false otherwise.
46   bool emitCheck(MachineBasicBlock &MBB,
47                  MachineBasicBlock::instr_iterator I) const;
48 };
49 
50 char X86KCFI::ID = 0;
51 } // end anonymous namespace
52 
INITIALIZE_PASS(X86KCFI,DEBUG_TYPE,X86_KCFI_PASS_NAME,false,false)53 INITIALIZE_PASS(X86KCFI, DEBUG_TYPE, X86_KCFI_PASS_NAME, false, false)
54 
55 FunctionPass *llvm::createX86KCFIPass() { return new X86KCFI(); }
56 
emitCheck(MachineBasicBlock & MBB,MachineBasicBlock::instr_iterator MBBI) const57 bool X86KCFI::emitCheck(MachineBasicBlock &MBB,
58                         MachineBasicBlock::instr_iterator MBBI) const {
59   assert(TII && "Target instruction info was not initialized");
60 
61   // If the call instruction is bundled, we can only emit a check safely if
62   // it's the first instruction in the bundle.
63   if (MBBI->isBundled() && !std::prev(MBBI)->isBundle())
64     report_fatal_error("Cannot emit a KCFI check for a bundled call");
65 
66   MachineFunction &MF = *MBB.getParent();
67   // If the call target is a memory operand, unfold it and use R11 for the
68   // call, so KCFI_CHECK won't have to recompute the address.
69   switch (MBBI->getOpcode()) {
70   case X86::CALL64m:
71   case X86::CALL64m_NT:
72   case X86::TAILJMPm64:
73   case X86::TAILJMPm64_REX: {
74     MachineBasicBlock::instr_iterator OrigCall = MBBI;
75     SmallVector<MachineInstr *, 2> NewMIs;
76     if (!TII->unfoldMemoryOperand(MF, *OrigCall, X86::R11, /*UnfoldLoad=*/true,
77                                   /*UnfoldStore=*/false, NewMIs))
78       report_fatal_error("Failed to unfold memory operand for a KCFI check");
79     for (auto *NewMI : NewMIs)
80       MBBI = MBB.insert(OrigCall, NewMI);
81     assert(MBBI->isCall() &&
82            "Unexpected instruction after memory operand unfolding");
83     if (OrigCall->shouldUpdateCallSiteInfo())
84       MF.moveCallSiteInfo(&*OrigCall, &*MBBI);
85     MBBI->setCFIType(MF, OrigCall->getCFIType());
86     OrigCall->eraseFromParent();
87     break;
88   }
89   default:
90     break;
91   }
92 
93   MachineInstr *Check =
94       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(X86::KCFI_CHECK))
95           .getInstr();
96   MachineOperand &Target = MBBI->getOperand(0);
97   switch (MBBI->getOpcode()) {
98   case X86::CALL64r:
99   case X86::CALL64r_NT:
100   case X86::TAILJMPr64:
101   case X86::TAILJMPr64_REX:
102     assert(Target.isReg() && "Unexpected target operand for an indirect call");
103     Check->addOperand(MachineOperand::CreateReg(Target.getReg(), false));
104     Target.setIsRenamable(false);
105     break;
106   case X86::CALL64pcrel32:
107   case X86::TAILJMPd64:
108     assert(Target.isSymbol() && "Unexpected target operand for a direct call");
109     // X86TargetLowering::EmitLoweredIndirectThunk always uses r11 for
110     // 64-bit indirect thunk calls.
111     assert(StringRef(Target.getSymbolName()).endswith("_r11") &&
112            "Unexpected register for an indirect thunk call");
113     Check->addOperand(MachineOperand::CreateReg(X86::R11, false));
114     break;
115   default:
116     llvm_unreachable("Unexpected CFI call opcode");
117   }
118 
119   Check->addOperand(MachineOperand::CreateImm(MBBI->getCFIType()));
120   MBBI->setCFIType(MF, 0);
121 
122   // If not already bundled, bundle the check and the call to prevent
123   // further changes.
124   if (!MBBI->isBundled())
125     finalizeBundle(MBB, Check->getIterator(), std::next(MBBI->getIterator()));
126 
127   ++NumKCFIChecksAdded;
128   return true;
129 }
130 
runOnMachineFunction(MachineFunction & MF)131 bool X86KCFI::runOnMachineFunction(MachineFunction &MF) {
132   const Module *M = MF.getMMI().getModule();
133   if (!M->getModuleFlag("kcfi"))
134     return false;
135 
136   const auto &SubTarget = MF.getSubtarget<X86Subtarget>();
137   TII = SubTarget.getInstrInfo();
138 
139   bool Changed = false;
140   for (MachineBasicBlock &MBB : MF) {
141     for (MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
142                                            MIE = MBB.instr_end();
143          MII != MIE; ++MII) {
144       if (MII->isCall() && MII->getCFIType())
145         Changed |= emitCheck(MBB, MII);
146     }
147   }
148 
149   return Changed;
150 }
151