Skip to content

Commit 955c40f

Browse files
committed
[llvm][fatlto] Add FatLTOCleanup pass
When using FatLTO, it is common to want to enable certain types of whole program optimizations (WPD) or security transforms (CFI), so that they can be made available when performing LTO. However, these transforms should not be used when compiling the non-LTO object code. Since the frontend must emit different IR, we cannot simply clone the module and optimize the LTO section and non-LTO section differently to work around this. Instead, we need to remove any problematic instruction sequences. This patch adds a new pass whose responsibility is to clean up the IR in the FatLTO pipeline after creating the bitcode section, which is after running the pre-link pipeline but before running module optimization. This allows us to safely drop any conflicting instructions or IR constructs that are inappropriate for non-LTO compilation.
1 parent d6315af commit 955c40f

File tree

8 files changed

+282
-0
lines changed

8 files changed

+282
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// COM: Prior to the introduction of the FatLTO cleanup pass, this used to cause
2+
// COM: the backend to crash, either due to an assertion failure, or because
3+
// COM: the CFI instructions couldn't be correctly generated. So, check to make
4+
// COM: sure that the FatLTO pipeline used by clang does not regress.
5+
6+
// COM: Check the generated IR doesn't contain llvm.type.checked.load in the final IR.
7+
// RUN: %clang_cc1 -O1 -emit-llvm -o - -ffat-lto-objects \
8+
// RUN: -fvisibility=hidden \
9+
// RUN: -fno-rtti -fsanitize=cfi-icall,cfi-mfcall,cfi-nvcall,cfi-vcall \
10+
// RUN: -fsanitize-trap=cfi-icall,cfi-mfcall,cfi-nvcall,cfi-vcall \
11+
// RUN: -fwhole-program-vtables %s 2>&1 | FileCheck %s --check-prefix=FATLTO
12+
13+
// COM: Note that the embedded bitcode section will contain references to
14+
// COM: llvm.type.checked.load, so we need to match the function body first.
15+
// FATLTO-LABEL: entry:
16+
// FATLTO-NEXT: %vtable = load ptr, ptr %p1
17+
// FATLTO-NOT: llvm.type.checked.load
18+
// FATLTO-NEXT: %vfunc = load ptr, ptr %vtable
19+
// FATLTO-NEXT: %call = tail call {{.*}} %vfunc(ptr {{.*}} %p1)
20+
// FATLTO-NEXT: ret void
21+
22+
// COM: Ensure that we don't crash in the backend anymore when clang uses
23+
// COM: CFI checks with -ffat-lto-objects.
24+
// RUN: %clang_cc1 -O1 --emit-codegen-only -ffat-lto-objects \
25+
// RUN: -fvisibility=hidden \
26+
// RUN: -fno-rtti -fsanitize=cfi-icall,cfi-mfcall,cfi-nvcall,cfi-vcall \
27+
// RUN: -fsanitize-trap=cfi-icall,cfi-mfcall,cfi-nvcall,cfi-vcall \
28+
// RUN: -fwhole-program-vtables %s
29+
30+
class a {
31+
public:
32+
virtual long b();
33+
};
34+
void c(a &p1) { p1.b(); }
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//===- FatLtoCleanup.h - clean up IR for the FatLTO pipeline ----*- C++ -*-===//
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 defines operations used to clean up IR for the FatLTO pipeline.
10+
// Instrumentation that is beneficial for bitcode sections used in LTO may
11+
// need to be cleaned up to finish non-LTO compilation. llvm.checked.load is
12+
// and example of an instruction that we want to preserve for LTO, but is
13+
// incorrect to leave unchanged during the per-TU compilation in FatLTO.
14+
//
15+
//===----------------------------------------------------------------------===//
16+
17+
#ifndef LLVM_TRANSFORMS_IPO_FATLTOCLEANUP_H
18+
#define LLVM_TRANSFORMS_IPO_FATLTOCLEANUP_H
19+
20+
#include "llvm/IR/PassManager.h"
21+
22+
namespace llvm {
23+
24+
class Module;
25+
class ModuleSummaryIndex;
26+
27+
28+
class FatLtoCleanup : public PassInfoMixin<FatLtoCleanup> {
29+
public:
30+
FatLtoCleanup() {}
31+
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
32+
};
33+
34+
} // end namespace llvm
35+
36+
#endif // LLVM_TRANSFORMS_IPO_FATLTOCLEANUP_H

llvm/lib/Passes/PassBuilder.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@
177177
#include "llvm/Transforms/IPO/ElimAvailExtern.h"
178178
#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
179179
#include "llvm/Transforms/IPO/ExpandVariadics.h"
180+
#include "llvm/Transforms/IPO/FatLTOCleanup.h"
180181
#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
181182
#include "llvm/Transforms/IPO/FunctionAttrs.h"
182183
#include "llvm/Transforms/IPO/FunctionImport.h"

llvm/lib/Passes/PassBuilderPipelines.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
#include "llvm/Transforms/IPO/ElimAvailExtern.h"
5454
#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
5555
#include "llvm/Transforms/IPO/ExpandVariadics.h"
56+
#include "llvm/Transforms/IPO/FatLTOCleanup.h"
5657
#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
5758
#include "llvm/Transforms/IPO/FunctionAttrs.h"
5859
#include "llvm/Transforms/IPO/GlobalDCE.h"
@@ -1651,6 +1652,12 @@ PassBuilder::buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO,
16511652
MPM.addPass(buildLTOPreLinkDefaultPipeline(Level));
16521653
MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
16531654

1655+
// Perform any cleanups to the IR that aren't suitable for per TU compilation,
1656+
// like removing CFI/WPD related instructions. Note, we reuse
1657+
// LowerTypeTestsPass to clean up type tests rather than duplicate that logic
1658+
// in FatLtoCleanup.
1659+
MPM.addPass(FatLtoCleanup());
1660+
16541661
// If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
16551662
// object code, only in the bitcode section, so drop it before we run
16561663
// module optimization and generate machine code. If llvm.type.test() isn't in

llvm/lib/Passes/PassRegistry.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ MODULE_PASS("lower-emutls", LowerEmuTLSPass())
9898
MODULE_PASS("lower-global-dtors", LowerGlobalDtorsPass())
9999
MODULE_PASS("lower-ifunc", LowerIFuncPass())
100100
MODULE_PASS("lowertypetests", LowerTypeTestsPass())
101+
MODULE_PASS("fatlto-cleanup", FatLtoCleanup())
101102
MODULE_PASS("pgo-force-function-attrs", PGOForceFunctionAttrsPass(PGOOpt ? PGOOpt->ColdOptType : PGOOptions::ColdFuncOpt::Default))
102103
MODULE_PASS("memprof-context-disambiguation", MemProfContextDisambiguation())
103104
MODULE_PASS("memprof-module", ModuleMemProfilerPass())

llvm/lib/Transforms/IPO/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ add_llvm_component_library(LLVMipo
1414
EmbedBitcodePass.cpp
1515
ExpandVariadics.cpp
1616
ExtractGV.cpp
17+
FatLTOCleanup.cpp
1718
ForceFunctionAttrs.cpp
1819
FunctionAttrs.cpp
1920
FunctionImport.cpp
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
//===- FatLtoCleanup.cpp - clean up IR for the FatLTO pipeline --*- C++ -*-===//
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 defines operations used to clean up IR for the FatLTO pipeline.
10+
// Instrumentation that is beneficial for bitcode sections used in LTO may
11+
// need to be cleaned up to finish non-LTO compilation. llvm.checked.load is
12+
// and example of an instruction that we want to preserve for LTO, but is
13+
// incorrect to leave unchanged during the per-TU compilation in FatLTO.
14+
//
15+
//===----------------------------------------------------------------------===//
16+
17+
#include "llvm/Transforms/IPO/FatLTOCleanup.h"
18+
#include "llvm/ADT/SetVector.h"
19+
#include "llvm/IR/Function.h"
20+
#include "llvm/IR/IRBuilder.h"
21+
#include "llvm/IR/Intrinsics.h"
22+
#include "llvm/IR/Module.h"
23+
#include "llvm/IR/PassManager.h"
24+
#include "llvm/IR/Use.h"
25+
#include "llvm/Support/Debug.h"
26+
27+
using namespace llvm;
28+
29+
#define DEBUG_TYPE "fatlto-cleanup"
30+
31+
namespace {
32+
// Replaces uses of llvm.type.checked.load instructions with unchecked loads.
33+
// In essence, we're undoing the frontends instrumentation, since it isn't
34+
// correct for the non-LTO part of a FatLTO object.
35+
//
36+
// llvm.type.checked.load instruction sequences always have a particular form:
37+
//
38+
// clang-format off
39+
//
40+
// %0 = tail call { ptr, i1 } @llvm.type.checked.load(ptr %vtable, i32 0, metadata !"foo"), !nosanitize !0
41+
// %1 = extractvalue { ptr, i1 } %0, 1, !nosanitize !0
42+
// br i1 %1, label %cont2, label %trap1, !nosanitize !0
43+
//
44+
// trap1: ; preds = %entry
45+
// tail call void @llvm.ubsantrap(i8 2) #3, !nosanitize !0
46+
// unreachable, !nosanitize !0
47+
//
48+
// cont2: ; preds = %entry
49+
// %2 = extractvalue { ptr, i1 } %0, 0, !nosanitize !0
50+
// %call = tail call noundef i64 %2(ptr noundef nonnull align 8 dereferenceable(8) %p1) #4
51+
//
52+
// clang-format on
53+
//
54+
// In this sequence, the vtable pointer is first loaded and checked against some
55+
// metadata. The result indicates failure, then the program traps. On the
56+
// success path, the pointer is used to make an indirect call to the function
57+
// pointer loaded from the vtable.
58+
//
59+
// Since we won't be able to lower this correctly later in non-LTO builds, we
60+
// need to drop the special load and trap, and emit a normal load of the
61+
// function pointer from the vtable.
62+
//
63+
// This is straight forward, since the checked load can be replaced w/ a load
64+
// of the vtable pointer and a GEP instruction to index into the vtable and get
65+
// the correct method/function pointer. We replace the "check" with a constant
66+
// indicating success, which allows later passes to simplify control flow and
67+
// remove any now dead instructions.
68+
//
69+
// This logic holds for both llvm.type.checked.load and
70+
// llvm.type.checked.load.relative instructions.
71+
static bool cleanUpTypeCheckedLoad(Module &M, Function &CheckedLoadFn) {
72+
bool Changed = false;
73+
// Use SetVector so we can rely on insertion order to drop instructions
74+
// in a safe order (e.g. uses before defs), and avoid adding instructions
75+
// to the drop set multiple times.
76+
SetVector<Instruction *> ToDrop;
77+
for (Use &U : llvm::make_early_inc_range(CheckedLoadFn.uses())) {
78+
for (auto *User : U->users()) {
79+
Instruction *I = dyn_cast<Instruction>(User);
80+
if (!I)
81+
continue;
82+
LLVM_DEBUG(dbgs() << "Checking candidate instruction" << *I << "\n");
83+
84+
IRBuilder<> IRB(I);
85+
Value *Ptr = I->getOperand(0);
86+
Value *Offset = I->getOperand(1);
87+
Type *Ty = I->getType()->getContainedType(0);
88+
// Use i8 so we can directly use the offset from llvm.type.checked.load.
89+
Value *Gep = IRB.CreateGEP(Type::getInt8Ty(M.getContext()), Ptr, Offset);
90+
LoadInst *L = IRB.CreateLoad(Ty, Gep, "vfunc");
91+
92+
bool Replaced = false;
93+
for (auto *MaybeEv : I->users()) {
94+
auto *EV = dyn_cast<ExtractValueInst>(MaybeEv);
95+
if (!EV)
96+
continue;
97+
98+
size_t Index = EV->getIndices()[0];
99+
if (Index == 0) {
100+
// If EV is extracting a vtable ptr, replace it w/ a direct load.
101+
LLVM_DEBUG(llvm::dbgs()
102+
<< "Replacing " << *EV << " with " << *L << "\n");
103+
EV->replaceAllUsesWith(L);
104+
ToDrop.insert(EV);
105+
LLVM_DEBUG(dbgs()
106+
<< DEBUG_TYPE << ": add " << *EV << "to drop set.\n");
107+
Replaced = true;
108+
} else if (Index == 1) {
109+
// If EV is extracting the boolean, replace it w/ a constant, so
110+
// that the branch to trap will be dropped later.
111+
ConstantInt *C = ConstantInt::getTrue(M.getContext());
112+
LLVM_DEBUG(llvm::dbgs() << DEBUG_TYPE << ": replacing " << *EV
113+
<< " with " << *C << "\n");
114+
EV->replaceAllUsesWith(C);
115+
ToDrop.insert(EV);
116+
LLVM_DEBUG(dbgs()
117+
<< DEBUG_TYPE << ": add " << *EV << "to drop set.\n");
118+
Replaced = true;
119+
}
120+
}
121+
if (Replaced) {
122+
LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": add " << *I << "to drop set.\n");
123+
ToDrop.insert(I);
124+
Changed = true;
125+
}
126+
}
127+
}
128+
for (Instruction *I : ToDrop) {
129+
LLVM_DEBUG(dbgs() << "Dropping instruction:" << *I << "\n");
130+
I->eraseFromParent();
131+
}
132+
if (Changed)
133+
CheckedLoadFn.eraseFromParent();
134+
return Changed;
135+
}
136+
} // namespace
137+
138+
PreservedAnalyses FatLtoCleanup::run(Module &M, ModuleAnalysisManager &AM) {
139+
Function *TypeCheckedLoadFn =
140+
Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load);
141+
Function *TypeCheckedLoadRelFn = Intrinsic::getDeclarationIfExists(
142+
&M, Intrinsic::type_checked_load_relative);
143+
144+
bool Changed = false;
145+
if (TypeCheckedLoadFn)
146+
Changed |= cleanUpTypeCheckedLoad(M, *TypeCheckedLoadFn);
147+
if (TypeCheckedLoadRelFn)
148+
Changed |= cleanUpTypeCheckedLoad(M, *TypeCheckedLoadRelFn);
149+
150+
if (Changed) {
151+
// M.dump();
152+
return PreservedAnalyses::none();
153+
}
154+
155+
return PreservedAnalyses::all();
156+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
; RUN: opt -passes="fatlto-cleanup" -mtriple=x86_64-unknown-fuchsia < %s -S | FileCheck %s
3+
4+
5+
6+
define hidden void @foo(ptr %p1) {
7+
entry:
8+
%vtable = load ptr, ptr %p1, align 8
9+
%0 = tail call { ptr, i1 } @llvm.type.checked.load(ptr %vtable, i32 0, metadata !"_ZTS1a")
10+
%1 = extractvalue { ptr, i1 } %0, 1
11+
br i1 %1, label %cont2, label %trap1
12+
13+
trap1:
14+
tail call void @llvm.ubsantrap(i8 2)
15+
unreachable
16+
17+
cont2:
18+
%2 = extractvalue { ptr, i1 } %0, 0
19+
%call = tail call noundef i64 %2(ptr noundef nonnull align 8 dereferenceable(8) %p1)
20+
ret void
21+
}
22+
23+
; CHECK-LABEL: define hidden void @foo
24+
; CHECK-NEXT: entry:
25+
; CHECK-NEXT: %vtable = load ptr, ptr %p1, align 8
26+
; CHECK-NEXT: %0 = getelementptr i8, ptr %vtable, i32 0
27+
; CHECK-NEXT: %vfunc = load ptr, ptr %0, align 8
28+
; CHECK-NEXT: br i1 true, label %cont2, label %trap1
29+
30+
; CHECK-LABEL: trap1:
31+
; CHECK-NEXT: tail call void @llvm.ubsantrap(i8 2)
32+
; CHECK-NEXT: unreachable
33+
34+
; CHECK-LABEL: cont2:
35+
; CHECK-NEXT: %call = tail call noundef i64 %vfunc(ptr noundef nonnull align 8 dereferenceable(8) %p1)
36+
; CHECK-NEXT: ret void
37+
; CHECK-NEXT:}
38+
39+
; Function Attrs: cold noreturn nounwind
40+
declare void @llvm.ubsantrap(i8 immarg) #0
41+
42+
; Function Attrs: nocallback nofree nosync nounwind willreturn memory(none)
43+
declare { ptr, i1 } @llvm.type.checked.load(ptr, i32, metadata) #1
44+
45+
attributes #0 = { cold noreturn nounwind }
46+
attributes #1 = { nocallback nofree nosync nounwind willreturn memory(none) }

0 commit comments

Comments
 (0)