[llvm-branch-commits] [llvm-branch] r324007 - Merging r323155:

Reid Kleckner via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Thu Feb 1 13:28:26 PST 2018


Author: rnk
Date: Thu Feb  1 13:28:26 2018
New Revision: 324007

URL: http://llvm.org/viewvc/llvm-project?rev=324007&view=rev
Log:
Merging r323155:
------------------------------------------------------------------------
r323155 | chandlerc | 2018-01-22 14:05:25 -0800 (Mon, 22 Jan 2018) | 133 lines

Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..

Summary:
First, we need to explain the core of the vulnerability. Note that this
is a very incomplete description, please see the Project Zero blog post
for details:
https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html

The basis for branch target injection is to direct speculative execution
of the processor to some "gadget" of executable code by poisoning the
prediction of indirect branches with the address of that gadget. The
gadget in turn contains an operation that provides a side channel for
reading data. Most commonly, this will look like a load of secret data
followed by a branch on the loaded value and then a load of some
predictable cache line. The attacker then uses timing of the processors
cache to determine which direction the branch took *in the speculative
execution*, and in turn what one bit of the loaded value was. Due to the
nature of these timing side channels and the branch predictor on Intel
processors, this allows an attacker to leak data only accessible to
a privileged domain (like the kernel) back into an unprivileged domain.

The goal is simple: avoid generating code which contains an indirect
branch that could have its prediction poisoned by an attacker. In many
cases, the compiler can simply use directed conditional branches and
a small search tree. LLVM already has support for lowering switches in
this way and the first step of this patch is to disable jump-table
lowering of switches and introduce a pass to rewrite explicit indirectbr
sequences into a switch over integers.

However, there is no fully general alternative to indirect calls. We
introduce a new construct we call a "retpoline" to implement indirect
calls in a non-speculatable way. It can be thought of loosely as
a trampoline for indirect calls which uses the RET instruction on x86.
Further, we arrange for a specific call->ret sequence which ensures the
processor predicts the return to go to a controlled, known location. The
retpoline then "smashes" the return address pushed onto the stack by the
call with the desired target of the original indirect call. The result
is a predicted return to the next instruction after a call (which can be
used to trap speculative execution within an infinite loop) and an
actual indirect branch to an arbitrary address.

On 64-bit x86 ABIs, this is especially easily done in the compiler by
using a guaranteed scratch register to pass the target into this device.
For 32-bit ABIs there isn't a guaranteed scratch register and so several
different retpoline variants are introduced to use a scratch register if
one is available in the calling convention and to otherwise use direct
stack push/pop sequences to pass the target address.

This "retpoline" mitigation is fully described in the following blog
post: https://support.google.com/faqs/answer/7625886

We also support a target feature that disables emission of the retpoline
thunk by the compiler to allow for custom thunks if users want them.
These are particularly useful in environments like kernels that
routinely do hot-patching on boot and want to hot-patch their thunk to
different code sequences. They can write this custom thunk and use
`-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
case, on x86-64 thu thunk names must be:
```
  __llvm_external_retpoline_r11
```
or on 32-bit:
```
  __llvm_external_retpoline_eax
  __llvm_external_retpoline_ecx
  __llvm_external_retpoline_edx
  __llvm_external_retpoline_push
```
And the target of the retpoline is passed in the named register, or in
the case of the `push` suffix on the top of the stack via a `pushl`
instruction.

There is one other important source of indirect branches in x86 ELF
binaries: the PLT. These patches also include support for LLD to
generate PLT entries that perform a retpoline-style indirection.

The only other indirect branches remaining that we are aware of are from
precompiled runtimes (such as crt0.o and similar). The ones we have
found are not really attackable, and so we have not focused on them
here, but eventually these runtimes should also be replicated for
retpoline-ed configurations for completeness.

For kernels or other freestanding or fully static executables, the
compiler switch `-mretpoline` is sufficient to fully mitigate this
particular attack. For dynamic executables, you must compile *all*
libraries with `-mretpoline` and additionally link the dynamic
executable and all shared libraries with LLD and pass `-z retpolineplt`
(or use similar functionality from some other linker). We strongly
recommend also using `-z now` as non-lazy binding allows the
retpoline-mitigated PLT to be substantially smaller.

When manually apply similar transformations to `-mretpoline` to the
Linux kernel we observed very small performance hits to applications
running typical workloads, and relatively minor hits (approximately 2%)
even for extremely syscall-heavy applications. This is largely due to
the small number of indirect branches that occur in performance
sensitive paths of the kernel.

When using these patches on statically linked applications, especially
C++ applications, you should expect to see a much more dramatic
performance hit. For microbenchmarks that are switch, indirect-, or
virtual-call heavy we have seen overheads ranging from 10% to 50%.

However, real-world workloads exhibit substantially lower performance
impact. Notably, techniques such as PGO and ThinLTO dramatically reduce
the impact of hot indirect calls (by speculatively promoting them to
direct calls) and allow optimized search trees to be used to lower
switches. If you need to deploy these techniques in C++ applications, we
*strongly* recommend that you ensure all hot call targets are statically
linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well
tuned servers using all of these techniques saw 5% - 10% overhead from
the use of retpoline.

We will add detailed documentation covering these components in
subsequent patches, but wanted to make the core functionality available
as soon as possible. Happy for more code review, but we'd really like to
get these patches landed and backported ASAP for obvious reasons. We're
planning to backport this to both 6.0 and 5.0 release streams and get
a 5.0 release with just this cherry picked ASAP for distros and vendors.

This patch is the work of a number of people over the past month: Eric, Reid,
Rui, and myself. I'm mailing it out as a single commit due to the time
sensitive nature of landing this and the need to backport it. Huge thanks to
everyone who helped out here, and everyone at Intel who helped out in
discussions about how to craft this. Also, credit goes to Paul Turner (at
Google, but not an LLVM contributor) for much of the underlying retpoline
design.

Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer

Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D41723
------------------------------------------------------------------------

Added:
    llvm/branches/release_50/lib/CodeGen/IndirectBrExpandPass.cpp
      - copied, changed from r323155, llvm/trunk/lib/CodeGen/IndirectBrExpandPass.cpp
    llvm/branches/release_50/lib/Target/X86/X86RetpolineThunks.cpp
      - copied unchanged from r323155, llvm/trunk/lib/Target/X86/X86RetpolineThunks.cpp
    llvm/branches/release_50/test/CodeGen/X86/retpoline-external.ll
      - copied unchanged from r323155, llvm/trunk/test/CodeGen/X86/retpoline-external.ll
    llvm/branches/release_50/test/CodeGen/X86/retpoline.ll
      - copied, changed from r323155, llvm/trunk/test/CodeGen/X86/retpoline.ll
    llvm/branches/release_50/test/Transforms/IndirectBrExpand/
      - copied from r323155, llvm/trunk/test/Transforms/IndirectBrExpand/
Modified:
    llvm/branches/release_50/   (props changed)
    llvm/branches/release_50/include/llvm/CodeGen/Passes.h
    llvm/branches/release_50/include/llvm/CodeGen/TargetPassConfig.h
    llvm/branches/release_50/include/llvm/InitializePasses.h
    llvm/branches/release_50/include/llvm/Target/TargetLowering.h
    llvm/branches/release_50/include/llvm/Target/TargetSubtargetInfo.h
    llvm/branches/release_50/lib/CodeGen/CMakeLists.txt
    llvm/branches/release_50/lib/CodeGen/CodeGen.cpp
    llvm/branches/release_50/lib/CodeGen/TargetPassConfig.cpp
    llvm/branches/release_50/lib/CodeGen/TargetSubtargetInfo.cpp
    llvm/branches/release_50/lib/Target/X86/CMakeLists.txt
    llvm/branches/release_50/lib/Target/X86/X86.h
    llvm/branches/release_50/lib/Target/X86/X86.td
    llvm/branches/release_50/lib/Target/X86/X86AsmPrinter.h
    llvm/branches/release_50/lib/Target/X86/X86FastISel.cpp
    llvm/branches/release_50/lib/Target/X86/X86FrameLowering.cpp
    llvm/branches/release_50/lib/Target/X86/X86ISelDAGToDAG.cpp
    llvm/branches/release_50/lib/Target/X86/X86ISelLowering.cpp
    llvm/branches/release_50/lib/Target/X86/X86ISelLowering.h
    llvm/branches/release_50/lib/Target/X86/X86InstrCompiler.td
    llvm/branches/release_50/lib/Target/X86/X86InstrControl.td
    llvm/branches/release_50/lib/Target/X86/X86InstrInfo.td
    llvm/branches/release_50/lib/Target/X86/X86MCInstLower.cpp
    llvm/branches/release_50/lib/Target/X86/X86Subtarget.cpp
    llvm/branches/release_50/lib/Target/X86/X86Subtarget.h
    llvm/branches/release_50/lib/Target/X86/X86TargetMachine.cpp
    llvm/branches/release_50/test/CodeGen/X86/O0-pipeline.ll
    llvm/branches/release_50/tools/opt/opt.cpp

Propchange: llvm/branches/release_50/
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Thu Feb  1 13:28:26 2018
@@ -1,2 +1,2 @@
-/llvm/trunk:313366
+/llvm/trunk:313366,323155
 /llvm/trunk:155241,308483-308484,308503,308808,308813,308847,308891,308906,308950,308963,308978,308986,309044,309071,309113,309120,309122,309140,309227,309302,309321,309323,309325,309330,309343,309353,309355,309422,309481,309483,309495,309555,309561,309594,309614,309651,309744,309758,309849,309928,309930,309945,310066,310071,310190,310240-310242,310250,310253,310262,310267,310481,310492,310498,310510,310534,310552,310604,310712,310779,310784,310796,310842,310906,310926,310939,310979,310988,310990-310991,311061,311068,311071,311087,311229,311258,311263,311387,311429,311554,311565,311572,311623,311835,312022,312285,313334:312337

Modified: llvm/branches/release_50/include/llvm/CodeGen/Passes.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/include/llvm/CodeGen/Passes.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/include/llvm/CodeGen/Passes.h (original)
+++ llvm/branches/release_50/include/llvm/CodeGen/Passes.h Thu Feb  1 13:28:26 2018
@@ -420,6 +420,9 @@ namespace llvm {
   /// shuffles.
   FunctionPass *createExpandReductionsPass();
 
+  // This pass expands indirectbr instructions.
+  FunctionPass *createIndirectBrExpandPass();
+
 } // End llvm namespace
 
 #endif

Modified: llvm/branches/release_50/include/llvm/CodeGen/TargetPassConfig.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/include/llvm/CodeGen/TargetPassConfig.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/include/llvm/CodeGen/TargetPassConfig.h (original)
+++ llvm/branches/release_50/include/llvm/CodeGen/TargetPassConfig.h Thu Feb  1 13:28:26 2018
@@ -406,6 +406,13 @@ protected:
   /// immediately before machine code is emitted.
   virtual void addPreEmitPass() { }
 
+  /// Targets may add passes immediately before machine code is emitted in this
+  /// callback. This is called even later than `addPreEmitPass`.
+  // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
+  // position and remove the `2` suffix here as this callback is what
+  // `addPreEmitPass` *should* be but in reality isn't.
+  virtual void addPreEmitPass2() {}
+
   /// Utilities for targets to add passes to the pass manager.
   ///
 

Modified: llvm/branches/release_50/include/llvm/InitializePasses.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/include/llvm/InitializePasses.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/include/llvm/InitializePasses.h (original)
+++ llvm/branches/release_50/include/llvm/InitializePasses.h Thu Feb  1 13:28:26 2018
@@ -157,6 +157,7 @@ void initializeIVUsersWrapperPassPass(Pa
 void initializeIfConverterPass(PassRegistry&);
 void initializeImplicitNullChecksPass(PassRegistry&);
 void initializeIndVarSimplifyLegacyPassPass(PassRegistry&);
+void initializeIndirectBrExpandPassPass(PassRegistry&);
 void initializeInductiveRangeCheckEliminationPass(PassRegistry&);
 void initializeInferAddressSpacesPass(PassRegistry&);
 void initializeInferFunctionAttrsLegacyPassPass(PassRegistry&);

Modified: llvm/branches/release_50/include/llvm/Target/TargetLowering.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/include/llvm/Target/TargetLowering.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/include/llvm/Target/TargetLowering.h (original)
+++ llvm/branches/release_50/include/llvm/Target/TargetLowering.h Thu Feb  1 13:28:26 2018
@@ -799,7 +799,7 @@ public:
   }
 
   /// Return true if lowering to a jump table is allowed.
-  bool areJTsAllowed(const Function *Fn) const {
+  virtual bool areJTsAllowed(const Function *Fn) const {
     if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
       return false;
 

Modified: llvm/branches/release_50/include/llvm/Target/TargetSubtargetInfo.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/include/llvm/Target/TargetSubtargetInfo.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/include/llvm/Target/TargetSubtargetInfo.h (original)
+++ llvm/branches/release_50/include/llvm/Target/TargetSubtargetInfo.h Thu Feb  1 13:28:26 2018
@@ -172,6 +172,9 @@ public:
   /// \brief True if the subtarget should run the atomic expansion pass.
   virtual bool enableAtomicExpand() const;
 
+  /// True if the subtarget should run the indirectbr expansion pass.
+  virtual bool enableIndirectBrExpand() const;
+
   /// \brief Override generic scheduling policy within a region.
   ///
   /// This is a convenient way for targets that don't provide any custom

Modified: llvm/branches/release_50/lib/CodeGen/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/CodeGen/CMakeLists.txt?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/CodeGen/CMakeLists.txt (original)
+++ llvm/branches/release_50/lib/CodeGen/CMakeLists.txt Thu Feb  1 13:28:26 2018
@@ -34,6 +34,7 @@ add_llvm_library(LLVMCodeGen
   GlobalMerge.cpp
   IfConversion.cpp
   ImplicitNullChecks.cpp
+  IndirectBrExpandPass.cpp
   InlineSpiller.cpp
   InterferenceCache.cpp
   InterleavedAccessPass.cpp

Modified: llvm/branches/release_50/lib/CodeGen/CodeGen.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/CodeGen/CodeGen.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/CodeGen/CodeGen.cpp (original)
+++ llvm/branches/release_50/lib/CodeGen/CodeGen.cpp Thu Feb  1 13:28:26 2018
@@ -39,6 +39,7 @@ void llvm::initializeCodeGen(PassRegistr
   initializeGCModuleInfoPass(Registry);
   initializeIfConverterPass(Registry);
   initializeImplicitNullChecksPass(Registry);
+  initializeIndirectBrExpandPassPass(Registry);
   initializeInterleavedAccessPass(Registry);
   initializeLiveDebugValuesPass(Registry);
   initializeLiveDebugVariablesPass(Registry);

Copied: llvm/branches/release_50/lib/CodeGen/IndirectBrExpandPass.cpp (from r323155, llvm/trunk/lib/CodeGen/IndirectBrExpandPass.cpp)
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/CodeGen/IndirectBrExpandPass.cpp?p2=llvm/branches/release_50/lib/CodeGen/IndirectBrExpandPass.cpp&p1=llvm/trunk/lib/CodeGen/IndirectBrExpandPass.cpp&r1=323155&r2=324007&rev=324007&view=diff
==============================================================================
--- llvm/trunk/lib/CodeGen/IndirectBrExpandPass.cpp (original)
+++ llvm/branches/release_50/lib/CodeGen/IndirectBrExpandPass.cpp Thu Feb  1 13:28:26 2018
@@ -30,7 +30,7 @@
 #include "llvm/ADT/Sequence.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/CodeGen/TargetPassConfig.h"
-#include "llvm/CodeGen/TargetSubtargetInfo.h"
+#include "llvm/Target/TargetSubtargetInfo.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"

Modified: llvm/branches/release_50/lib/CodeGen/TargetPassConfig.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/CodeGen/TargetPassConfig.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/CodeGen/TargetPassConfig.cpp (original)
+++ llvm/branches/release_50/lib/CodeGen/TargetPassConfig.cpp Thu Feb  1 13:28:26 2018
@@ -790,6 +790,9 @@ void TargetPassConfig::addMachinePasses(
   if (EnableMachineOutliner)
     PM->add(createMachineOutlinerPass());
 
+  // Add passes that directly emit MI after all other MI passes.
+  addPreEmitPass2();
+
   AddingMachinePasses = false;
 }
 

Modified: llvm/branches/release_50/lib/CodeGen/TargetSubtargetInfo.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/CodeGen/TargetSubtargetInfo.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/CodeGen/TargetSubtargetInfo.cpp (original)
+++ llvm/branches/release_50/lib/CodeGen/TargetSubtargetInfo.cpp Thu Feb  1 13:28:26 2018
@@ -37,6 +37,10 @@ bool TargetSubtargetInfo::enableAtomicEx
   return true;
 }
 
+bool TargetSubtargetInfo::enableIndirectBrExpand() const {
+  return false;
+}
+
 bool TargetSubtargetInfo::enableMachineScheduler() const {
   return false;
 }

Modified: llvm/branches/release_50/lib/Target/X86/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/CMakeLists.txt?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/CMakeLists.txt (original)
+++ llvm/branches/release_50/lib/Target/X86/CMakeLists.txt Thu Feb  1 13:28:26 2018
@@ -57,6 +57,7 @@ set(sources
   X86OptimizeLEAs.cpp
   X86PadShortFunction.cpp
   X86RegisterInfo.cpp
+  X86RetpolineThunks.cpp
   X86SelectionDAGInfo.cpp
   X86ShuffleDecodeConstantPool.cpp
   X86Subtarget.cpp

Modified: llvm/branches/release_50/lib/Target/X86/X86.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86.h (original)
+++ llvm/branches/release_50/lib/Target/X86/X86.h Thu Feb  1 13:28:26 2018
@@ -22,6 +22,7 @@ namespace llvm {
 class FunctionPass;
 class ImmutablePass;
 class InstructionSelector;
+class ModulePass;
 class PassRegistry;
 class X86RegisterBankInfo;
 class X86Subtarget;
@@ -98,6 +99,9 @@ void initializeFixupBWInstPassPass(PassR
 /// encoding when possible in order to reduce code size.
 FunctionPass *createX86EvexToVexInsts();
 
+/// This pass creates the thunks for the retpoline feature.
+ModulePass *createX86RetpolineThunksPass();
+
 InstructionSelector *createX86InstructionSelector(const X86TargetMachine &TM,
                                                   X86Subtarget &,
                                                   X86RegisterBankInfo &);

Modified: llvm/branches/release_50/lib/Target/X86/X86.td
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86.td?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86.td (original)
+++ llvm/branches/release_50/lib/Target/X86/X86.td Thu Feb  1 13:28:26 2018
@@ -290,6 +290,27 @@ def FeatureERMSB
           "ermsb", "HasERMSB", "true",
           "REP MOVS/STOS are fast">;
 
+// Enable mitigation of some aspects of speculative execution related
+// vulnerabilities by removing speculatable indirect branches. This disables
+// jump-table formation, rewrites explicit `indirectbr` instructions into
+// `switch` instructions, and uses a special construct called a "retpoline" to
+// prevent speculation of the remaining indirect branches (indirect calls and
+// tail calls).
+def FeatureRetpoline
+    : SubtargetFeature<"retpoline", "UseRetpoline", "true",
+                       "Remove speculation of indirect branches from the "
+                       "generated code, either by avoiding them entirely or "
+                       "lowering them with a speculation blocking construct.">;
+
+// Rely on external thunks for the emitted retpoline calls. This allows users
+// to provide their own custom thunk definitions in highly specialized
+// environments such as a kernel that does boot-time hot patching.
+def FeatureRetpolineExternalThunk
+    : SubtargetFeature<
+          "retpoline-external-thunk", "UseRetpolineExternalThunk", "true",
+          "Enable retpoline, but with an externally provided thunk.",
+          [FeatureRetpoline]>;
+
 //===----------------------------------------------------------------------===//
 // X86 processors supported.
 //===----------------------------------------------------------------------===//

Modified: llvm/branches/release_50/lib/Target/X86/X86AsmPrinter.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86AsmPrinter.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86AsmPrinter.h (original)
+++ llvm/branches/release_50/lib/Target/X86/X86AsmPrinter.h Thu Feb  1 13:28:26 2018
@@ -30,6 +30,7 @@ class LLVM_LIBRARY_VISIBILITY X86AsmPrin
   StackMaps SM;
   FaultMaps FM;
   std::unique_ptr<MCCodeEmitter> CodeEmitter;
+  bool NeedsRetpoline = false;
 
   // This utility class tracks the length of a stackmap instruction's 'shadow'.
   // It is used by the X86AsmPrinter to ensure that the stackmap shadow

Modified: llvm/branches/release_50/lib/Target/X86/X86FastISel.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86FastISel.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86FastISel.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86FastISel.cpp Thu Feb  1 13:28:26 2018
@@ -3161,6 +3161,10 @@ bool X86FastISel::fastLowerCall(CallLowe
       (CalledFn && CalledFn->hasFnAttribute("no_caller_saved_registers")))
     return false;
 
+  // Functions using retpoline should use SDISel for calls.
+  if (Subtarget->useRetpoline())
+    return false;
+
   // Handle only C, fastcc, and webkit_js calling conventions for now.
   switch (CC) {
   default: return false;

Modified: llvm/branches/release_50/lib/Target/X86/X86FrameLowering.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86FrameLowering.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86FrameLowering.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86FrameLowering.cpp Thu Feb  1 13:28:26 2018
@@ -742,6 +742,11 @@ void X86FrameLowering::emitStackProbeCal
                                           bool InProlog) const {
   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
 
+  // FIXME: Add retpoline support and remove this.
+  if (Is64Bit && IsLargeCodeModel && STI.useRetpoline())
+    report_fatal_error("Emitting stack probe calls on 64-bit with the large "
+                       "code model and retpoline not yet implemented.");
+
   unsigned CallOp;
   if (Is64Bit)
     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
@@ -2337,6 +2342,10 @@ void X86FrameLowering::adjustForSegmente
     // This solution is not perfect, as it assumes that the .rodata section
     // is laid out within 2^31 bytes of each function body, but this seems
     // to be sufficient for JIT.
+    // FIXME: Add retpoline support and remove the error here..
+    if (STI.useRetpoline())
+      report_fatal_error("Emitting morestack calls on 64-bit with the large "
+                         "code model and retpoline not yet implemented.");
     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
         .addReg(X86::RIP)
         .addImm(0)

Modified: llvm/branches/release_50/lib/Target/X86/X86ISelDAGToDAG.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86ISelDAGToDAG.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86ISelDAGToDAG.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86ISelDAGToDAG.cpp Thu Feb  1 13:28:26 2018
@@ -550,11 +550,11 @@ void X86DAGToDAGISel::PreprocessISelDAG(
     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
 
     if (OptLevel != CodeGenOpt::None &&
-        // Only does this when target favors doesn't favor register indirect
-        // call.
+        // Only do this when the target can fold the load into the call or
+        // jmp.
+        !Subtarget->useRetpoline() &&
         ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
          (N->getOpcode() == X86ISD::TC_RETURN &&
-          // Only does this if load can be folded into TC_RETURN.
           (Subtarget->is64Bit() ||
            !getTargetMachine().isPositionIndependent())))) {
       /// Also try moving call address load from outside callseq_start to just

Modified: llvm/branches/release_50/lib/Target/X86/X86ISelLowering.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86ISelLowering.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86ISelLowering.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86ISelLowering.cpp Thu Feb  1 13:28:26 2018
@@ -24994,6 +24994,15 @@ X86TargetLowering::isVectorClearMaskLega
   return isShuffleMaskLegal(Mask, VT);
 }
 
+bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
+  // If the subtarget is using retpolines, we need to not generate jump tables.
+  if (Subtarget.useRetpoline())
+    return false;
+
+  // Otherwise, fallback on the generic logic.
+  return TargetLowering::areJTsAllowed(Fn);
+}
+
 //===----------------------------------------------------------------------===//
 //                           X86 Scheduler Hooks
 //===----------------------------------------------------------------------===//
@@ -26225,6 +26234,115 @@ X86TargetLowering::EmitLoweredTLSCall(Ma
   return BB;
 }
 
+static unsigned getOpcodeForRetpoline(unsigned RPOpc) {
+  switch (RPOpc) {
+  case X86::RETPOLINE_CALL32:
+    return X86::CALLpcrel32;
+  case X86::RETPOLINE_CALL64:
+    return X86::CALL64pcrel32;
+  case X86::RETPOLINE_TCRETURN32:
+    return X86::TCRETURNdi;
+  case X86::RETPOLINE_TCRETURN64:
+    return X86::TCRETURNdi64;
+  }
+  llvm_unreachable("not retpoline opcode");
+}
+
+static const char *getRetpolineSymbol(const X86Subtarget &Subtarget,
+                                      unsigned Reg) {
+  switch (Reg) {
+  case 0:
+    assert(!Subtarget.is64Bit() && "R11 should always be available on x64");
+    return Subtarget.useRetpolineExternalThunk()
+               ? "__llvm_external_retpoline_push"
+               : "__llvm_retpoline_push";
+  case X86::EAX:
+    return Subtarget.useRetpolineExternalThunk()
+               ? "__llvm_external_retpoline_eax"
+               : "__llvm_retpoline_eax";
+  case X86::ECX:
+    return Subtarget.useRetpolineExternalThunk()
+               ? "__llvm_external_retpoline_ecx"
+               : "__llvm_retpoline_ecx";
+  case X86::EDX:
+    return Subtarget.useRetpolineExternalThunk()
+               ? "__llvm_external_retpoline_edx"
+               : "__llvm_retpoline_edx";
+  case X86::R11:
+    return Subtarget.useRetpolineExternalThunk()
+               ? "__llvm_external_retpoline_r11"
+               : "__llvm_retpoline_r11";
+  }
+  llvm_unreachable("unexpected reg for retpoline");
+}
+
+MachineBasicBlock *
+X86TargetLowering::EmitLoweredRetpoline(MachineInstr &MI,
+                                        MachineBasicBlock *BB) const {
+  // Copy the virtual register into the R11 physical register and
+  // call the retpoline thunk.
+  DebugLoc DL = MI.getDebugLoc();
+  const X86InstrInfo *TII = Subtarget.getInstrInfo();
+  unsigned CalleeVReg = MI.getOperand(0).getReg();
+  unsigned Opc = getOpcodeForRetpoline(MI.getOpcode());
+
+  // Find an available scratch register to hold the callee. On 64-bit, we can
+  // just use R11, but we scan for uses anyway to ensure we don't generate
+  // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
+  // already a register use operand to the call to hold the callee. If none
+  // are available, push the callee instead. This is less efficient, but is
+  // necessary for functions using 3 regparms. Such function calls are
+  // (currently) not eligible for tail call optimization, because there is no
+  // scratch register available to hold the address of the callee.
+  SmallVector<unsigned, 3> AvailableRegs;
+  if (Subtarget.is64Bit())
+    AvailableRegs.push_back(X86::R11);
+  else
+    AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX});
+
+  // Zero out any registers that are already used.
+  for (const auto &MO : MI.operands()) {
+    if (MO.isReg() && MO.isUse())
+      for (unsigned &Reg : AvailableRegs)
+        if (Reg == MO.getReg())
+          Reg = 0;
+  }
+
+  // Choose the first remaining non-zero available register.
+  unsigned AvailableReg = 0;
+  for (unsigned MaybeReg : AvailableRegs) {
+    if (MaybeReg) {
+      AvailableReg = MaybeReg;
+      break;
+    }
+  }
+
+  const char *Symbol = getRetpolineSymbol(Subtarget, AvailableReg);
+
+  if (AvailableReg == 0) {
+    // No register available. Use PUSH. This must not be a tailcall, and this
+    // must not be x64.
+    if (Subtarget.is64Bit())
+      report_fatal_error(
+          "Cannot make an indirect call on x86-64 using both retpoline and a "
+          "calling convention that preservers r11");
+    if (Opc != X86::CALLpcrel32)
+      report_fatal_error("Cannot make an indirect tail call on x86 using "
+                         "retpoline without a preserved register");
+    BuildMI(*BB, MI, DL, TII->get(X86::PUSH32r)).addReg(CalleeVReg);
+    MI.getOperand(0).ChangeToES(Symbol);
+    MI.setDesc(TII->get(Opc));
+  } else {
+    BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
+        .addReg(CalleeVReg);
+    MI.getOperand(0).ChangeToES(Symbol);
+    MI.setDesc(TII->get(Opc));
+    MachineInstrBuilder(*BB->getParent(), &MI)
+        .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
+  }
+  return BB;
+}
+
 MachineBasicBlock *
 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
                                     MachineBasicBlock *MBB) const {
@@ -26689,6 +26807,11 @@ X86TargetLowering::EmitInstrWithCustomIn
   case X86::TLS_base_addr32:
   case X86::TLS_base_addr64:
     return EmitLoweredTLSAddr(MI, BB);
+  case X86::RETPOLINE_CALL32:
+  case X86::RETPOLINE_CALL64:
+  case X86::RETPOLINE_TCRETURN32:
+  case X86::RETPOLINE_TCRETURN64:
+    return EmitLoweredRetpoline(MI, BB);
   case X86::CATCHRET:
     return EmitLoweredCatchRet(MI, BB);
   case X86::CATCHPAD:

Modified: llvm/branches/release_50/lib/Target/X86/X86ISelLowering.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86ISelLowering.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86ISelLowering.h (original)
+++ llvm/branches/release_50/lib/Target/X86/X86ISelLowering.h Thu Feb  1 13:28:26 2018
@@ -986,6 +986,9 @@ namespace llvm {
     bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
                                 EVT VT) const override;
 
+    /// Returns true if lowering to a jump table is allowed.
+    bool areJTsAllowed(const Function *Fn) const override;
+
     /// If true, then instruction selection should
     /// seek to shrink the FP constant of the specified type to a smaller type
     /// in order to save space and / or reduce runtime.
@@ -1289,6 +1292,9 @@ namespace llvm {
     MachineBasicBlock *EmitLoweredTLSCall(MachineInstr &MI,
                                           MachineBasicBlock *BB) const;
 
+    MachineBasicBlock *EmitLoweredRetpoline(MachineInstr &MI,
+                                            MachineBasicBlock *BB) const;
+
     MachineBasicBlock *emitEHSjLjSetJmp(MachineInstr &MI,
                                         MachineBasicBlock *MBB) const;
 

Modified: llvm/branches/release_50/lib/Target/X86/X86InstrCompiler.td
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86InstrCompiler.td?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86InstrCompiler.td (original)
+++ llvm/branches/release_50/lib/Target/X86/X86InstrCompiler.td Thu Feb  1 13:28:26 2018
@@ -1106,14 +1106,14 @@ def X86tcret_6regs : PatFrag<(ops node:$
 
 def : Pat<(X86tcret ptr_rc_tailcall:$dst, imm:$off),
           (TCRETURNri ptr_rc_tailcall:$dst, imm:$off)>,
-          Requires<[Not64BitMode]>;
+          Requires<[Not64BitMode, NotUseRetpoline]>;
 
 // FIXME: This is disabled for 32-bit PIC mode because the global base
 // register which is part of the address mode may be assigned a
 // callee-saved register.
 def : Pat<(X86tcret (load addr:$dst), imm:$off),
           (TCRETURNmi addr:$dst, imm:$off)>,
-          Requires<[Not64BitMode, IsNotPIC]>;
+          Requires<[Not64BitMode, IsNotPIC, NotUseRetpoline]>;
 
 def : Pat<(X86tcret (i32 tglobaladdr:$dst), imm:$off),
           (TCRETURNdi tglobaladdr:$dst, imm:$off)>,
@@ -1125,13 +1125,21 @@ def : Pat<(X86tcret (i32 texternalsym:$d
 
 def : Pat<(X86tcret ptr_rc_tailcall:$dst, imm:$off),
           (TCRETURNri64 ptr_rc_tailcall:$dst, imm:$off)>,
-          Requires<[In64BitMode]>;
+          Requires<[In64BitMode, NotUseRetpoline]>;
 
 // Don't fold loads into X86tcret requiring more than 6 regs.
 // There wouldn't be enough scratch registers for base+index.
 def : Pat<(X86tcret_6regs (load addr:$dst), imm:$off),
           (TCRETURNmi64 addr:$dst, imm:$off)>,
-          Requires<[In64BitMode]>;
+          Requires<[In64BitMode, NotUseRetpoline]>;
+
+def : Pat<(X86tcret ptr_rc_tailcall:$dst, imm:$off),
+          (RETPOLINE_TCRETURN64 ptr_rc_tailcall:$dst, imm:$off)>,
+          Requires<[In64BitMode, UseRetpoline]>;
+
+def : Pat<(X86tcret ptr_rc_tailcall:$dst, imm:$off),
+          (RETPOLINE_TCRETURN32 ptr_rc_tailcall:$dst, imm:$off)>,
+          Requires<[Not64BitMode, UseRetpoline]>;
 
 def : Pat<(X86tcret (i64 tglobaladdr:$dst), imm:$off),
           (TCRETURNdi64 tglobaladdr:$dst, imm:$off)>,

Modified: llvm/branches/release_50/lib/Target/X86/X86InstrControl.td
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86InstrControl.td?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86InstrControl.td (original)
+++ llvm/branches/release_50/lib/Target/X86/X86InstrControl.td Thu Feb  1 13:28:26 2018
@@ -211,11 +211,12 @@ let isCall = 1 in
                       Sched<[WriteJumpLd]>;
     def CALL32r     : I<0xFF, MRM2r, (outs), (ins GR32:$dst),
                         "call{l}\t{*}$dst", [(X86call GR32:$dst)], IIC_CALL_RI>,
-                      OpSize32, Requires<[Not64BitMode]>, Sched<[WriteJump]>;
+                      OpSize32, Requires<[Not64BitMode,NotUseRetpoline]>,
+                      Sched<[WriteJump]>;
     def CALL32m     : I<0xFF, MRM2m, (outs), (ins i32mem:$dst),
                         "call{l}\t{*}$dst", [(X86call (loadi32 addr:$dst))],
                         IIC_CALL_MEM>, OpSize32,
-                      Requires<[Not64BitMode,FavorMemIndirectCall]>,
+                      Requires<[Not64BitMode,FavorMemIndirectCall,NotUseRetpoline]>,
                       Sched<[WriteJumpLd]>;
 
     let Predicates = [Not64BitMode] in {
@@ -298,11 +299,12 @@ let isCall = 1, Uses = [RSP], SchedRW =
   def CALL64r       : I<0xFF, MRM2r, (outs), (ins GR64:$dst),
                         "call{q}\t{*}$dst", [(X86call GR64:$dst)],
                         IIC_CALL_RI>,
-                      Requires<[In64BitMode]>;
+                      Requires<[In64BitMode,NotUseRetpoline]>;
   def CALL64m       : I<0xFF, MRM2m, (outs), (ins i64mem:$dst),
                         "call{q}\t{*}$dst", [(X86call (loadi64 addr:$dst))],
                         IIC_CALL_MEM>,
-                      Requires<[In64BitMode,FavorMemIndirectCall]>;
+                      Requires<[In64BitMode,FavorMemIndirectCall,
+                                NotUseRetpoline]>;
 
   def FARCALL64   : RI<0xFF, MRM3m, (outs), (ins opaque80mem:$dst),
                        "lcall{q}\t{*}$dst", [], IIC_CALL_FAR_MEM>;
@@ -341,6 +343,27 @@ let isCall = 1, isTerminator = 1, isRetu
   }
 }
 
+let isPseudo = 1, isCall = 1, isCodeGenOnly = 1,
+    Uses = [RSP],
+    usesCustomInserter = 1,
+    SchedRW = [WriteJump] in {
+  def RETPOLINE_CALL32 :
+    PseudoI<(outs), (ins GR32:$dst), [(X86call GR32:$dst)]>,
+            Requires<[Not64BitMode,UseRetpoline]>;
+
+  def RETPOLINE_CALL64 :
+    PseudoI<(outs), (ins GR64:$dst), [(X86call GR64:$dst)]>,
+            Requires<[In64BitMode,UseRetpoline]>;
+
+  // Retpoline variant of indirect tail calls.
+  let isTerminator = 1, isReturn = 1, isBarrier = 1 in {
+    def RETPOLINE_TCRETURN64 :
+      PseudoI<(outs), (ins GR64:$dst, i32imm:$offset), []>;
+    def RETPOLINE_TCRETURN32 :
+      PseudoI<(outs), (ins GR32:$dst, i32imm:$offset), []>;
+  }
+}
+
 // Conditional tail calls are similar to the above, but they are branches
 // rather than barriers, and they use EFLAGS.
 let isCall = 1, isTerminator = 1, isReturn = 1, isBranch = 1,

Modified: llvm/branches/release_50/lib/Target/X86/X86InstrInfo.td
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86InstrInfo.td?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86InstrInfo.td (original)
+++ llvm/branches/release_50/lib/Target/X86/X86InstrInfo.td Thu Feb  1 13:28:26 2018
@@ -917,6 +917,8 @@ def HasFastLZCNT : Predicate<"Subtarget-
 def HasFastSHLDRotate : Predicate<"Subtarget->hasFastSHLDRotate()">;
 def HasERMSB : Predicate<"Subtarget->hasERMSB()">;
 def HasMFence    : Predicate<"Subtarget->hasMFence()">;
+def UseRetpoline : Predicate<"Subtarget->useRetpoline()">;
+def NotUseRetpoline : Predicate<"!Subtarget->useRetpoline()">;
 
 //===----------------------------------------------------------------------===//
 // X86 Instruction Format Definitions.

Modified: llvm/branches/release_50/lib/Target/X86/X86MCInstLower.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86MCInstLower.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86MCInstLower.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86MCInstLower.cpp Thu Feb  1 13:28:26 2018
@@ -874,6 +874,10 @@ void X86AsmPrinter::LowerSTATEPOINT(cons
       // address is to far away. (TODO: support non-relative addressing)
       break;
     case MachineOperand::MO_Register:
+      // FIXME: Add retpoline support and remove this.
+      if (Subtarget->useRetpoline())
+        report_fatal_error("Lowering register statepoints with retpoline not "
+                           "yet implemented.");
       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
       CallOpcode = X86::CALL64r;
       break;
@@ -1028,6 +1032,10 @@ void X86AsmPrinter::LowerPATCHPOINT(cons
 
     EmitAndCountInstruction(
         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
+    // FIXME: Add retpoline support and remove this.
+    if (Subtarget->useRetpoline())
+      report_fatal_error(
+          "Lowering patchpoint with retpoline not yet implemented.");
     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
   }
 

Modified: llvm/branches/release_50/lib/Target/X86/X86Subtarget.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86Subtarget.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86Subtarget.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86Subtarget.cpp Thu Feb  1 13:28:26 2018
@@ -315,6 +315,8 @@ void X86Subtarget::initializeEnvironment
   HasCLFLUSHOPT = false;
   HasCLWB = false;
   IsBTMemSlow = false;
+  UseRetpoline = false;
+  UseRetpolineExternalThunk = false;
   IsPMULLDSlow = false;
   IsSHLDSlow = false;
   IsUAMem16Slow = false;

Modified: llvm/branches/release_50/lib/Target/X86/X86Subtarget.h
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86Subtarget.h?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86Subtarget.h (original)
+++ llvm/branches/release_50/lib/Target/X86/X86Subtarget.h Thu Feb  1 13:28:26 2018
@@ -297,6 +297,14 @@ protected:
   /// Processor supports Cache Line Write Back instruction
   bool HasCLWB;
 
+  /// Use a retpoline thunk rather than indirect calls to block speculative
+  /// execution.
+  bool UseRetpoline;
+
+  /// When using a retpoline thunk, call an externally provided thunk rather
+  /// than emitting one inside the compiler.
+  bool UseRetpolineExternalThunk;
+
   /// Use software floating point for code generation.
   bool UseSoftFloat;
 
@@ -506,6 +514,8 @@ public:
   bool hasPKU() const { return HasPKU; }
   bool hasMPX() const { return HasMPX; }
   bool hasCLFLUSHOPT() const { return HasCLFLUSHOPT; }
+  bool useRetpoline() const { return UseRetpoline; }
+  bool useRetpolineExternalThunk() const { return UseRetpolineExternalThunk; }
 
   bool isXRaySupported() const override { return is64Bit(); }
 
@@ -639,6 +649,10 @@ public:
   /// compiler runtime or math libraries.
   bool hasSinCos() const;
 
+  /// If we are using retpolines, we need to expand indirectbr to avoid it
+  /// lowering to an actual indirect jump.
+  bool enableIndirectBrExpand() const override { return useRetpoline(); }
+
   /// Enable the MachineScheduler pass for all X86 subtargets.
   bool enableMachineScheduler() const override { return true; }
 

Modified: llvm/branches/release_50/lib/Target/X86/X86TargetMachine.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/lib/Target/X86/X86TargetMachine.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/lib/Target/X86/X86TargetMachine.cpp (original)
+++ llvm/branches/release_50/lib/Target/X86/X86TargetMachine.cpp Thu Feb  1 13:28:26 2018
@@ -305,6 +305,7 @@ public:
   void addPreRegAlloc() override;
   void addPostRegAlloc() override;
   void addPreEmitPass() override;
+  void addPreEmitPass2() override;
   void addPreSched2() override;
 };
 
@@ -334,6 +335,11 @@ void X86PassConfig::addIRPasses() {
 
   if (TM->getOptLevel() != CodeGenOpt::None)
     addPass(createInterleavedAccessPass());
+
+  // Add passes that handle indirect branch removal and insertion of a retpoline
+  // thunk. These will be a no-op unless a function subtarget has the retpoline
+  // feature enabled.
+  addPass(createIndirectBrExpandPass());
 }
 
 bool X86PassConfig::addInstSelector() {
@@ -418,3 +424,7 @@ void X86PassConfig::addPreEmitPass() {
     addPass(createX86EvexToVexInsts());
   }
 }
+
+void X86PassConfig::addPreEmitPass2() {
+  addPass(createX86RetpolineThunksPass());
+}

Modified: llvm/branches/release_50/test/CodeGen/X86/O0-pipeline.ll
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/test/CodeGen/X86/O0-pipeline.ll?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/test/CodeGen/X86/O0-pipeline.ll (original)
+++ llvm/branches/release_50/test/CodeGen/X86/O0-pipeline.ll Thu Feb  1 13:28:26 2018
@@ -25,6 +25,7 @@
 ; CHECK-NEXT:       Inserts calls to mcount-like functions
 ; CHECK-NEXT:       Scalarize Masked Memory Intrinsics
 ; CHECK-NEXT:       Expand reduction intrinsics
+; CHECK-NEXT:       Expand indirectbr instructions
 ; CHECK-NEXT:     Rewrite Symbols
 ; CHECK-NEXT:     FunctionPass Manager
 ; CHECK-NEXT:       Dominator Tree Construction
@@ -55,6 +56,8 @@
 ; CHECK-NEXT:       Machine Natural Loop Construction
 ; CHECK-NEXT:       Insert XRay ops
 ; CHECK-NEXT:       Implement the 'patchable-function' attribute
+; CHECK-NEXT:     X86 Retpoline Thunks
+; CHECK-NEXT:     FunctionPass Manager
 ; CHECK-NEXT:       Lazy Machine Block Frequency Analysis
 ; CHECK-NEXT:       Machine Optimization Remark Emitter
 ; CHECK-NEXT:       MachineDominator Tree Construction

Copied: llvm/branches/release_50/test/CodeGen/X86/retpoline.ll (from r323155, llvm/trunk/test/CodeGen/X86/retpoline.ll)
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/test/CodeGen/X86/retpoline.ll?p2=llvm/branches/release_50/test/CodeGen/X86/retpoline.ll&p1=llvm/trunk/test/CodeGen/X86/retpoline.ll&r1=323155&r2=324007&rev=324007&view=diff
==============================================================================
--- llvm/trunk/test/CodeGen/X86/retpoline.ll (original)
+++ llvm/branches/release_50/test/CodeGen/X86/retpoline.ll Thu Feb  1 13:28:26 2018
@@ -164,23 +164,19 @@ define void @nonlazybind_caller() #0 {
   ret void
 }
 
+; nonlazybind wasn't implemented in LLVM 5.0, so this looks the same as direct.
 ; X64-LABEL: nonlazybind_caller:
-; X64:       movq nonlazybind_callee at GOTPCREL(%rip), %[[REG:.*]]
-; X64:       movq %[[REG]], %r11
-; X64:       callq __llvm_retpoline_r11
-; X64:       movq %[[REG]], %r11
-; X64:       jmp __llvm_retpoline_r11 # TAILCALL
+; X64:       callq nonlazybind_callee
+; X64:       jmp nonlazybind_callee # TAILCALL
 ; X64FAST-LABEL: nonlazybind_caller:
-; X64FAST:   movq nonlazybind_callee at GOTPCREL(%rip), %r11
-; X64FAST:   callq __llvm_retpoline_r11
-; X64FAST:   movq nonlazybind_callee at GOTPCREL(%rip), %r11
-; X64FAST:   jmp __llvm_retpoline_r11 # TAILCALL
+; X64FAST:   callq nonlazybind_callee
+; X64FAST:   jmp nonlazybind_callee # TAILCALL
 ; X86-LABEL: nonlazybind_caller:
-; X86:       calll nonlazybind_callee at PLT
-; X86:       jmp nonlazybind_callee at PLT # TAILCALL
+; X86:       calll nonlazybind_callee
+; X86:       jmp nonlazybind_callee # TAILCALL
 ; X86FAST-LABEL: nonlazybind_caller:
-; X86FAST:   calll nonlazybind_callee at PLT
-; X86FAST:   jmp nonlazybind_callee at PLT # TAILCALL
+; X86FAST:   calll nonlazybind_callee
+; X86FAST:   jmp nonlazybind_callee # TAILCALL
 
 
 @indirectbr_rewrite.targets = constant [10 x i8*] [i8* blockaddress(@indirectbr_rewrite, %bb0),

Modified: llvm/branches/release_50/tools/opt/opt.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/branches/release_50/tools/opt/opt.cpp?rev=324007&r1=324006&r2=324007&view=diff
==============================================================================
--- llvm/branches/release_50/tools/opt/opt.cpp (original)
+++ llvm/branches/release_50/tools/opt/opt.cpp Thu Feb  1 13:28:26 2018
@@ -401,6 +401,7 @@ int main(int argc, char **argv) {
   initializeSjLjEHPreparePass(Registry);
   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
   initializeGlobalMergePass(Registry);
+  initializeIndirectBrExpandPassPass(Registry);
   initializeInterleavedAccessPass(Registry);
   initializeCountingFunctionInserterPass(Registry);
   initializeUnreachableBlockElimLegacyPassPass(Registry);




More information about the llvm-branch-commits mailing list