LLVM  5.0.0
NVPTXTargetMachine.cpp
Go to the documentation of this file.
1 //===-- NVPTXTargetMachine.cpp - Define TargetMachine for NVPTX -----------===//
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 // Top-level implementation for the NVPTX target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "NVPTXTargetMachine.h"
15 #include "NVPTX.h"
16 #include "NVPTXAllocaHoisting.h"
17 #include "NVPTXLowerAggrCopies.h"
18 #include "NVPTXTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Pass.h"
32 #include "llvm/Transforms/Scalar.h"
35 #include <cassert>
36 #include <string>
37 
38 using namespace llvm;
39 
40 // LSV is still relatively new; this switch lets us turn it off in case we
41 // encounter (or suspect) a bug.
42 static cl::opt<bool>
43  DisableLoadStoreVectorizer("disable-nvptx-load-store-vectorizer",
44  cl::desc("Disable load/store vectorizer"),
45  cl::init(false), cl::Hidden);
46 
47 namespace llvm {
48 
57 
58 } // end namespace llvm
59 
60 extern "C" void LLVMInitializeNVPTXTarget() {
61  // Register the target.
64 
65  // FIXME: This pass is really intended to be invoked during IR optimization,
66  // but it's very NVPTX-specific.
76 }
77 
78 static std::string computeDataLayout(bool is64Bit) {
79  std::string Ret = "e";
80 
81  if (!is64Bit)
82  Ret += "-p:32:32";
83 
84  Ret += "-i64:64-v16:16-v32:32-n16:32:64";
85 
86  return Ret;
87 }
88 
90  StringRef CPU, StringRef FS,
91  const TargetOptions &Options,
94  CodeGenOpt::Level OL, bool is64bit)
95  // The pic relocation model is used regardless of what the client has
96  // specified, as it is the only relocation model currently supported.
97  : LLVMTargetMachine(T, computeDataLayout(is64bit), TT, CPU, FS, Options,
98  Reloc::PIC_, CM, OL),
99  is64bit(is64bit),
100  TLOF(llvm::make_unique<NVPTXTargetObjectFile>()),
101  Subtarget(TT, CPU, FS, *this) {
102  if (TT.getOS() == Triple::NVCL)
103  drvInterface = NVPTX::NVCL;
104  else
105  drvInterface = NVPTX::CUDA;
106  initAsmInfo();
107 }
108 
110 
111 void NVPTXTargetMachine32::anchor() {}
112 
114  StringRef CPU, StringRef FS,
115  const TargetOptions &Options,
117  CodeModel::Model CM,
119  : NVPTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
120 
121 void NVPTXTargetMachine64::anchor() {}
122 
124  StringRef CPU, StringRef FS,
125  const TargetOptions &Options,
127  CodeModel::Model CM,
129  : NVPTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
130 
131 namespace {
132 
133 class NVPTXPassConfig : public TargetPassConfig {
134 public:
135  NVPTXPassConfig(NVPTXTargetMachine &TM, PassManagerBase &PM)
136  : TargetPassConfig(TM, PM) {}
137 
138  NVPTXTargetMachine &getNVPTXTargetMachine() const {
139  return getTM<NVPTXTargetMachine>();
140  }
141 
142  void addIRPasses() override;
143  bool addInstSelector() override;
144  void addPostRegAlloc() override;
145  void addMachineSSAOptimization() override;
146 
147  FunctionPass *createTargetRegisterAllocator(bool) override;
148  void addFastRegAlloc(FunctionPass *RegAllocPass) override;
149  void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override;
150 
151 private:
152  // If the opt level is aggressive, add GVN; otherwise, add EarlyCSE. This
153  // function is only called in opt mode.
154  void addEarlyCSEOrGVNPass();
155 
156  // Add passes that propagate special memory spaces.
157  void addAddressSpaceInferencePasses();
158 
159  // Add passes that perform straight-line scalar optimizations.
160  void addStraightLineScalarOptimizationPasses();
161 };
162 
163 } // end anonymous namespace
164 
166  return new NVPTXPassConfig(*this, PM);
167 }
168 
170  Builder.addExtension(
172  [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
174  PM.add(createNVVMIntrRangePass(Subtarget.getSmVersion()));
175  });
176 }
177 
179  return TargetIRAnalysis([this](const Function &F) {
180  return TargetTransformInfo(NVPTXTTIImpl(this, F));
181  });
182 }
183 
184 void NVPTXPassConfig::addEarlyCSEOrGVNPass() {
185  if (getOptLevel() == CodeGenOpt::Aggressive)
186  addPass(createGVNPass());
187  else
188  addPass(createEarlyCSEPass());
189 }
190 
191 void NVPTXPassConfig::addAddressSpaceInferencePasses() {
192  // NVPTXLowerArgs emits alloca for byval parameters which can often
193  // be eliminated by SROA.
194  addPass(createSROAPass());
195  addPass(createNVPTXLowerAllocaPass());
196  addPass(createInferAddressSpacesPass());
197 }
198 
199 void NVPTXPassConfig::addStraightLineScalarOptimizationPasses() {
202  // ReassociateGEPs exposes more opportunites for SLSR. See
203  // the example in reassociate-geps-and-slsr.ll.
205  // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
206  // EarlyCSE can reuse. GVN generates significantly better code than EarlyCSE
207  // for some of our benchmarks.
208  addEarlyCSEOrGVNPass();
209  // Run NaryReassociate after EarlyCSE/GVN to be more effective.
210  addPass(createNaryReassociatePass());
211  // NaryReassociate on GEPs creates redundant common expressions, so run
212  // EarlyCSE after it.
213  addPass(createEarlyCSEPass());
214 }
215 
216 void NVPTXPassConfig::addIRPasses() {
217  // The following passes are known to not play well with virtual regs hanging
218  // around after register allocation (which in our case, is *all* registers).
219  // We explicitly disable them here. We do, however, need some functionality
220  // of the PrologEpilogCodeInserter pass, so we emulate that behavior in the
221  // NVPTXPrologEpilog pass (see NVPTXPrologEpilogPass.cpp).
222  disablePass(&PrologEpilogCodeInserterID);
223  disablePass(&MachineCopyPropagationID);
224  disablePass(&TailDuplicateID);
225  disablePass(&StackMapLivenessID);
226  disablePass(&LiveDebugValuesID);
227  disablePass(&PostRASchedulerID);
228  disablePass(&FuncletLayoutID);
229  disablePass(&PatchableFunctionID);
230 
231  // NVVMReflectPass is added in addEarlyAsPossiblePasses, so hopefully running
232  // it here does nothing. But since we need it for correctness when lowering
233  // to NVPTX, run it here too, in case whoever built our pass pipeline didn't
234  // call addEarlyAsPossiblePasses.
235  addPass(createNVVMReflectPass());
236 
237  if (getOptLevel() != CodeGenOpt::None)
240  addPass(createGenericToNVVMPass());
241 
242  // NVPTXLowerArgs is required for correctness and should be run right
243  // before the address space inference passes.
244  addPass(createNVPTXLowerArgsPass(&getNVPTXTargetMachine()));
245  if (getOptLevel() != CodeGenOpt::None) {
246  addAddressSpaceInferencePasses();
249  addStraightLineScalarOptimizationPasses();
250  }
251 
252  // === LSR and other generic IR passes ===
254  // EarlyCSE is not always strong enough to clean up what LSR produces. For
255  // example, GVN can combine
256  //
257  // %0 = add %a, %b
258  // %1 = add %b, %a
259  //
260  // and
261  //
262  // %0 = shl nsw %a, 2
263  // %1 = shl %a, 2
264  //
265  // but EarlyCSE can do neither of them.
266  if (getOptLevel() != CodeGenOpt::None)
267  addEarlyCSEOrGVNPass();
268 }
269 
270 bool NVPTXPassConfig::addInstSelector() {
271  const NVPTXSubtarget &ST = *getTM<NVPTXTargetMachine>().getSubtargetImpl();
272 
273  addPass(createLowerAggrCopies());
274  addPass(createAllocaHoisting());
275  addPass(createNVPTXISelDag(getNVPTXTargetMachine(), getOptLevel()));
276 
277  if (!ST.hasImageHandles())
279 
280  return false;
281 }
282 
283 void NVPTXPassConfig::addPostRegAlloc() {
284  addPass(createNVPTXPrologEpilogPass(), false);
285  if (getOptLevel() != CodeGenOpt::None) {
286  // NVPTXPrologEpilogPass calculates frame object offset and replace frame
287  // index with VRFrame register. NVPTXPeephole need to be run after that and
288  // will replace VRFrame with VRFrameLocal when possible.
289  addPass(createNVPTXPeephole());
290  }
291 }
292 
293 FunctionPass *NVPTXPassConfig::createTargetRegisterAllocator(bool) {
294  return nullptr; // No reg alloc
295 }
296 
297 void NVPTXPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
298  assert(!RegAllocPass && "NVPTX uses no regalloc!");
299  addPass(&PHIEliminationID);
300  addPass(&TwoAddressInstructionPassID);
301 }
302 
303 void NVPTXPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
304  assert(!RegAllocPass && "NVPTX uses no regalloc!");
305 
306  addPass(&ProcessImplicitDefsID);
307  addPass(&LiveVariablesID);
308  addPass(&MachineLoopInfoID);
309  addPass(&PHIEliminationID);
310 
311  addPass(&TwoAddressInstructionPassID);
312  addPass(&RegisterCoalescerID);
313 
314  // PreRA instruction scheduling.
315  if (addPass(&MachineSchedulerID))
316  printAndVerify("After Machine Scheduling");
317 
318 
319  addPass(&StackSlotColoringID);
320 
321  // FIXME: Needs physical registers
322  //addPass(&PostRAMachineLICMID);
323 
324  printAndVerify("After StackSlotColoring");
325 }
326 
327 void NVPTXPassConfig::addMachineSSAOptimization() {
328  // Pre-ra tail duplication.
329  if (addPass(&EarlyTailDuplicateID))
330  printAndVerify("After Pre-RegAlloc TailDuplicate");
331 
332  // Optimize PHIs before DCE: removing dead PHI cycles may make more
333  // instructions dead.
334  addPass(&OptimizePHIsID);
335 
336  // This pass merges large allocas. StackSlotColoring is a different pass
337  // which merges spill slots.
338  addPass(&StackColoringID);
339 
340  // If the target requests it, assign local variables to stack slots relative
341  // to one another and simplify frame index references where possible.
342  addPass(&LocalStackSlotAllocationID);
343 
344  // With optimization, dead code should already be eliminated. However
345  // there is one known exception: lowered code for arguments that are only
346  // used by tail calls, where the tail calls reuse the incoming stack
347  // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
349  printAndVerify("After codegen DCE pass");
350 
351  // Allow targets to insert passes that improve instruction level parallelism,
352  // like if-conversion. Such passes will typically need dominator trees and
353  // loop info, just like LICM and CSE below.
354  if (addILPOpts())
355  printAndVerify("After ILP optimizations");
356 
357  addPass(&MachineLICMID);
358  addPass(&MachineCSEID);
359 
360  addPass(&MachineSinkingID);
361  printAndVerify("After Machine LICM, CSE and Sinking passes");
362 
363  addPass(&PeepholeOptimizerID);
364  printAndVerify("After codegen peephole optimization pass");
365 }
FunctionPass * createSpeculativeExecutionPass()
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:290
FunctionPass * createStraightLineStrengthReducePass()
FunctionPass * createGVNPass(bool NoLoads=false)
Create a legacy GVN pass.
Definition: GVN.cpp:2364
void initializeNVPTXLowerArgsPass(PassRegistry &)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
void LLVMInitializeNVPTXTarget()
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
FunctionPass * createNVVMReflectPass()
Definition: NVVMReflect.cpp:61
char & MachineLICMID
MachineLICM - This pass performs LICM on machine instructions.
ModulePass * createNVPTXAssignValidGlobalNamesPass()
char & FuncletLayoutID
This pass lays out funclets contiguously.
static std::string computeDataLayout(bool is64Bit)
FunctionPass * createAllocaHoisting()
char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
Analysis pass providing the TargetTransformInfo.
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
MachineFunctionPass * createNVPTXPrologEpilogPass()
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
ModulePass * createGenericToNVVMPass()
char & ProcessImplicitDefsID
ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
void initializeNVPTXAssignValidGlobalNamesPass(PassRegistry &)
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
char & StackColoringID
StackSlotColoring - This pass performs stack coloring and merging.
Pass * createLoadStoreVectorizerPass()
Target-Independent Code Generator Pass Configuration Options.
Target & getTheNVPTXTarget64()
#define F(x, y, z)
Definition: MD5.cpp:55
char & MachineCSEID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:110
unsigned int getSmVersion() const
TargetIRAnalysis getTargetIRAnalysis() override
Get a TargetIRAnalysis implementation for the target.
char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
FunctionPass * createNVPTXImageOptimizerPass()
void initializeNVVMIntrRangePass(PassRegistry &)
char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions...
Target & getTheNVPTXTarget32()
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
Function Alias Analysis false
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
This file a TargetTransformInfo::Concept conforming object specific to the NVPTX target machine...
NVPTXTargetMachine32(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM, CodeGenOpt::Level OL)
FunctionPass * createSeparateConstOffsetFromGEPPass(const TargetMachine *TM=nullptr, bool LowerGEP=false)
void initializeNVPTXLowerAggrCopiesPass(PassRegistry &)
void initializeNVVMReflectPass(PassRegistry &)
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:943
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
static bool is64Bit(const char *name)
MachineFunctionPass * createNVPTXReplaceImageHandlesPass()
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
char & LiveDebugValuesID
LiveDebugValues pass.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
void initializeNVPTXAllocaHoistingPass(PassRegistry &)
char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
void initializeGenericToNVVMPass(PassRegistry &)
EP_EarlyAsPossible - This extension point allows adding passes before any other transformations, allowing them to see the code as it is coming out of the frontend.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
char & PostRASchedulerID
createPostRAScheduler - This pass performs post register allocation scheduling.
void initializeNVPTXLowerAllocaPass(PassRegistry &)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
BasicBlockPass * createNVPTXLowerAllocaPass()
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
char & TailDuplicateID
TailDuplicate - Duplicate blocks with unconditional branches into tails of their predecessors.
char & MachineSinkingID
MachineSinking - This pass performs sinking on machine instructions.
char & OptimizePHIsID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...
Target - Wrapper for Target specific information.
char & PeepholeOptimizerID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
Basic Alias true
char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
FunctionPass * createInferAddressSpacesPass()
NVPTXTargetMachine.
MachineFunctionPass * createNVPTXPeephole()
FunctionPass * createNVPTXISelDag(NVPTXTargetMachine &TM, llvm::CodeGenOpt::Level OptLevel)
createNVPTXISelDag - This pass converts a legalized DAG into a NVPTX-specific DAG, ready for instruction scheduling.
~NVPTXTargetMachine() override
FunctionPass * createNVVMIntrRangePass(unsigned int SmVersion)
FunctionPass * createNVPTXLowerArgsPass(const NVPTXTargetMachine *TM)
FunctionPass * createLowerAggrCopies()
void adjustPassManager(PassManagerBuilder &) override
Allow the target to modify the pass manager, e.g.
FunctionPass * createSROAPass()
Definition: SROA.cpp:4312
NVPTXTargetMachine64(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM, CodeGenOpt::Level OL)
char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasImageHandles() const
RegisterTargetMachine - Helper template for registering a target machine implementation, for use in the target machine initialization function.
FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
Definition: EarlyCSE.cpp:1086
static cl::opt< bool > DisableLoadStoreVectorizer("disable-nvptx-load-store-vectorizer", cl::desc("Disable load/store vectorizer"), cl::init(false), cl::Hidden)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:40
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
This pass exposes codegen information to IR-level passes.
void addExtension(ExtensionPointTy Ty, ExtensionFn Fn)
char & LocalStackSlotAllocationID
LocalStackSlotAllocation - This pass assigns local frame indices to stack slots relative to one anoth...
FunctionPass * createNaryReassociatePass()
NVPTXTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM, CodeGenOpt::Level OP, bool is64bit)