blob: 0a0fbc7ac03c01541993cd79e1eb043b9c8691e9 [file] [log] [blame]
Michael Gottesman3923bec2013-08-12 21:02:02 +00001//===-- SelectionDAGBuilder.h - Selection-DAG building --------*- C++ -*---===//
Dan Gohman575fad32008-09-03 16:12:24 +00002//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
Benjamin Kramera7c40ef2014-08-13 16:26:38 +000014#ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
15#define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
Dan Gohman575fad32008-09-03 16:12:24 +000016
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "StatepointLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000018#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/DenseMap.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth802d7552012-12-04 07:12:27 +000021#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman575fad32008-09-03 16:12:24 +000022#include "llvm/CodeGen/SelectionDAGNodes.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000025#include "llvm/IR/Statepoint.h"
Torok Edwin56d06592009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Juergen Ributzkafd4633e2014-10-16 21:26:35 +000027#include "llvm/Target/TargetLowering.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000028#include <utility>
Dan Gohman575fad32008-09-03 16:12:24 +000029#include <vector>
Dan Gohman575fad32008-09-03 16:12:24 +000030
31namespace llvm {
32
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +000033class AddrSpaceCastInst;
Dan Gohman575fad32008-09-03 16:12:24 +000034class AllocaInst;
35class BasicBlock;
36class BitCastInst;
37class BranchInst;
38class CallInst;
Devang Patelb12ff592010-08-26 23:35:15 +000039class DbgValueInst;
Dan Gohman575fad32008-09-03 16:12:24 +000040class ExtractElementInst;
41class ExtractValueInst;
42class FCmpInst;
43class FPExtInst;
44class FPToSIInst;
45class FPToUIInst;
46class FPTruncInst;
Dan Gohman575fad32008-09-03 16:12:24 +000047class Function;
Dan Gohmana3624b62009-11-23 17:16:22 +000048class FunctionLoweringInfo;
Dan Gohman575fad32008-09-03 16:12:24 +000049class GetElementPtrInst;
50class GCFunctionInfo;
51class ICmpInst;
52class IntToPtrInst;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +000053class IndirectBrInst;
Dan Gohman575fad32008-09-03 16:12:24 +000054class InvokeInst;
55class InsertElementInst;
56class InsertValueInst;
57class Instruction;
58class LoadInst;
59class MachineBasicBlock;
Dan Gohman575fad32008-09-03 16:12:24 +000060class MachineInstr;
Dan Gohman575fad32008-09-03 16:12:24 +000061class MachineRegisterInfo;
Evan Cheng6e822452010-04-28 23:08:54 +000062class MDNode;
Patrik Hagglund1da35122014-03-12 08:00:24 +000063class MVT;
Dan Gohman575fad32008-09-03 16:12:24 +000064class PHINode;
65class PtrToIntInst;
66class ReturnInst;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +000067class SDDbgValue;
Dan Gohman575fad32008-09-03 16:12:24 +000068class SExtInst;
69class SelectInst;
70class ShuffleVectorInst;
71class SIToFPInst;
72class StoreInst;
73class SwitchInst;
Micah Villmowcdfe20b2012-10-08 16:38:25 +000074class DataLayout;
Owen Andersonbb15fec2011-12-08 22:15:21 +000075class TargetLibraryInfo;
Dan Gohman575fad32008-09-03 16:12:24 +000076class TargetLowering;
77class TruncInst;
78class UIToFPInst;
79class UnreachableInst;
Dan Gohman575fad32008-09-03 16:12:24 +000080class VAArgInst;
81class ZExtInst;
82
Dan Gohman575fad32008-09-03 16:12:24 +000083//===----------------------------------------------------------------------===//
Dan Gohman1a6c47f2009-11-23 18:04:58 +000084/// SelectionDAGBuilder - This is the common target-independent lowering
Dan Gohman575fad32008-09-03 16:12:24 +000085/// implementation that is parameterized by a TargetLowering object.
Dan Gohman575fad32008-09-03 16:12:24 +000086///
Benjamin Kramer079b96e2013-09-11 18:05:11 +000087class SelectionDAGBuilder {
Andrew Trick175143b2013-05-25 02:20:36 +000088 /// CurInst - The current instruction being visited
89 const Instruction *CurInst;
Dale Johannesendb7c5f62009-01-31 02:22:37 +000090
Dan Gohman575fad32008-09-03 16:12:24 +000091 DenseMap<const Value*, SDValue> NodeMap;
Andrew Trickd4d1d9c2013-10-31 17:18:07 +000092
Devang Patelb0c76392010-06-01 19:59:01 +000093 /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
94 /// to preserve debug information for incoming arguments.
95 DenseMap<const Value*, SDValue> UnusedArgNodeMap;
Dan Gohman575fad32008-09-03 16:12:24 +000096
Dale Johannesenbfd4fd72010-07-16 00:02:08 +000097 /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
98 class DanglingDebugInfo {
Devang Patelb12ff592010-08-26 23:35:15 +000099 const DbgValueInst* DI;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000100 DebugLoc dl;
101 unsigned SDNodeOrder;
102 public:
Craig Topperada08572014-04-16 04:21:27 +0000103 DanglingDebugInfo() : DI(nullptr), dl(DebugLoc()), SDNodeOrder(0) { }
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000104 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO)
105 : DI(di), dl(std::move(DL)), SDNodeOrder(SDNO) {}
Devang Patelb12ff592010-08-26 23:35:15 +0000106 const DbgValueInst* getDI() { return DI; }
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000107 DebugLoc getdl() { return dl; }
108 unsigned getSDNodeOrder() { return SDNodeOrder; }
109 };
110
111 /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
112 /// yet seen the referent. We defer handling these until we do see it.
113 DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
114
Chris Lattner1a32ede2009-12-24 00:37:38 +0000115public:
Dan Gohman575fad32008-09-03 16:12:24 +0000116 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
117 /// them up and then emit token factor nodes when possible. This allows us to
118 /// get simple disambiguation between loads without worrying about alias
119 /// analysis.
120 SmallVector<SDValue, 8> PendingLoads;
Philip Reames1a1bdb22014-12-02 18:50:36 +0000121
122 /// State used while lowering a statepoint sequence (gc_statepoint,
123 /// gc_relocate, and gc_result). See StatepointLowering.hpp/cpp for details.
124 StatepointLoweringState StatepointLowering;
Chris Lattner1a32ede2009-12-24 00:37:38 +0000125private:
Dan Gohman575fad32008-09-03 16:12:24 +0000126
127 /// PendingExports - CopyToReg nodes that copy values to virtual registers
128 /// for export to other blocks need to be emitted before any terminator
129 /// instruction, but they have no other ordering requirements. We bunch them
130 /// up and the emit a single tokenfactor for them just before terminator
131 /// instructions.
132 SmallVector<SDValue, 8> PendingExports;
133
Bill Wendling022d18f2009-12-18 23:32:53 +0000134 /// SDNodeOrder - A unique monotonically increasing number used to order the
135 /// SDNodes we create.
136 unsigned SDNodeOrder;
137
Hans Wennborg0867b152015-04-23 16:45:24 +0000138 enum CaseClusterKind {
139 /// A cluster of adjacent case labels with the same destination, or just one
140 /// case.
141 CC_Range,
142 /// A cluster of cases suitable for jump table lowering.
143 CC_JumpTable,
144 /// A cluster of cases suitable for bit test lowering.
145 CC_BitTests
146 };
Dan Gohman575fad32008-09-03 16:12:24 +0000147
Hans Wennborg0867b152015-04-23 16:45:24 +0000148 /// A cluster of case labels.
149 struct CaseCluster {
150 CaseClusterKind Kind;
151 const ConstantInt *Low, *High;
152 union {
153 MachineBasicBlock *MBB;
154 unsigned JTCasesIndex;
155 unsigned BTCasesIndex;
156 };
Cong Hou1938f2e2015-11-24 08:51:23 +0000157 BranchProbability Prob;
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000158
Hans Wennborg0867b152015-04-23 16:45:24 +0000159 static CaseCluster range(const ConstantInt *Low, const ConstantInt *High,
Cong Hou1938f2e2015-11-24 08:51:23 +0000160 MachineBasicBlock *MBB, BranchProbability Prob) {
Hans Wennborg0867b152015-04-23 16:45:24 +0000161 CaseCluster C;
162 C.Kind = CC_Range;
163 C.Low = Low;
164 C.High = High;
165 C.MBB = MBB;
Cong Hou1938f2e2015-11-24 08:51:23 +0000166 C.Prob = Prob;
Hans Wennborg0867b152015-04-23 16:45:24 +0000167 return C;
168 }
169
170 static CaseCluster jumpTable(const ConstantInt *Low,
171 const ConstantInt *High, unsigned JTCasesIndex,
Cong Hou1938f2e2015-11-24 08:51:23 +0000172 BranchProbability Prob) {
Hans Wennborg0867b152015-04-23 16:45:24 +0000173 CaseCluster C;
174 C.Kind = CC_JumpTable;
175 C.Low = Low;
176 C.High = High;
177 C.JTCasesIndex = JTCasesIndex;
Cong Hou1938f2e2015-11-24 08:51:23 +0000178 C.Prob = Prob;
Hans Wennborg0867b152015-04-23 16:45:24 +0000179 return C;
180 }
181
182 static CaseCluster bitTests(const ConstantInt *Low, const ConstantInt *High,
Cong Hou1938f2e2015-11-24 08:51:23 +0000183 unsigned BTCasesIndex, BranchProbability Prob) {
Hans Wennborg0867b152015-04-23 16:45:24 +0000184 CaseCluster C;
185 C.Kind = CC_BitTests;
186 C.Low = Low;
187 C.High = High;
188 C.BTCasesIndex = BTCasesIndex;
Cong Hou1938f2e2015-11-24 08:51:23 +0000189 C.Prob = Prob;
Hans Wennborg0867b152015-04-23 16:45:24 +0000190 return C;
Dan Gohman575fad32008-09-03 16:12:24 +0000191 }
192 };
193
Hans Wennborg0867b152015-04-23 16:45:24 +0000194 typedef std::vector<CaseCluster> CaseClusterVector;
195 typedef CaseClusterVector::iterator CaseClusterIt;
196
Dan Gohman575fad32008-09-03 16:12:24 +0000197 struct CaseBits {
198 uint64_t Mask;
199 MachineBasicBlock* BB;
200 unsigned Bits;
Cong Hou1938f2e2015-11-24 08:51:23 +0000201 BranchProbability ExtraProb;
Dan Gohman575fad32008-09-03 16:12:24 +0000202
Manman Rencf104462012-08-24 18:14:27 +0000203 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits,
Cong Hou1938f2e2015-11-24 08:51:23 +0000204 BranchProbability Prob):
205 Mask(mask), BB(bb), Bits(bits), ExtraProb(Prob) { }
Hans Wennborg0867b152015-04-23 16:45:24 +0000206
Cong Hou1938f2e2015-11-24 08:51:23 +0000207 CaseBits() : Mask(0), BB(nullptr), Bits(0) {}
Dan Gohman575fad32008-09-03 16:12:24 +0000208 };
209
Hans Wennborg0867b152015-04-23 16:45:24 +0000210 typedef std::vector<CaseBits> CaseBitsVector;
Dan Gohman575fad32008-09-03 16:12:24 +0000211
Hans Wennborg0867b152015-04-23 16:45:24 +0000212 /// Sort Clusters and merge adjacent cases.
213 void sortAndRangeify(CaseClusterVector &Clusters);
Anton Korobeynikov6f219132008-12-23 22:25:27 +0000214
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000215 /// CaseBlock - This structure is used to communicate between
216 /// SelectionDAGBuilder and SDISel for the code generation of additional basic
217 /// blocks needed by multi-case switch statements.
Dan Gohman575fad32008-09-03 16:12:24 +0000218 struct CaseBlock {
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000219 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
Cong Hou1938f2e2015-11-24 08:51:23 +0000220 const Value *cmpmiddle, MachineBasicBlock *truebb,
221 MachineBasicBlock *falsebb, MachineBasicBlock *me,
222 BranchProbability trueprob = BranchProbability::getUnknown(),
223 BranchProbability falseprob = BranchProbability::getUnknown())
224 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
225 TrueBB(truebb), FalseBB(falsebb), ThisBB(me), TrueProb(trueprob),
226 FalseProb(falseprob) {}
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000227
Dan Gohman575fad32008-09-03 16:12:24 +0000228 // CC - the condition code to use for the case block's setcc node
229 ISD::CondCode CC;
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000230
Dan Gohman575fad32008-09-03 16:12:24 +0000231 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
232 // Emit by default LHS op RHS. MHS is used for range comparisons:
233 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000234 const Value *CmpLHS, *CmpMHS, *CmpRHS;
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000235
Dan Gohman575fad32008-09-03 16:12:24 +0000236 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
237 MachineBasicBlock *TrueBB, *FalseBB;
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000238
Dan Gohman575fad32008-09-03 16:12:24 +0000239 // ThisBB - the block into which to emit the code for the setcc and branches
240 MachineBasicBlock *ThisBB;
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000241
Cong Hou1938f2e2015-11-24 08:51:23 +0000242 // TrueProb/FalseProb - branch weights.
243 BranchProbability TrueProb, FalseProb;
Dan Gohman575fad32008-09-03 16:12:24 +0000244 };
Jakub Staszak0480a8f2011-07-29 22:25:21 +0000245
Dan Gohman575fad32008-09-03 16:12:24 +0000246 struct JumpTable {
247 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
248 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
Andrew Trickd4d1d9c2013-10-31 17:18:07 +0000249
Dan Gohman575fad32008-09-03 16:12:24 +0000250 /// Reg - the virtual register containing the index of the jump table entry
251 //. to jump to.
252 unsigned Reg;
253 /// JTI - the JumpTableIndex for this jump table in the function.
254 unsigned JTI;
255 /// MBB - the MBB into which to emit the code for the indirect jump.
256 MachineBasicBlock *MBB;
257 /// Default - the MBB of the default bb, which is a successor of the range
258 /// check MBB. This is when updating PHI nodes in successors.
259 MachineBasicBlock *Default;
260 };
261 struct JumpTableHeader {
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000262 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000263 bool E = false)
264 : First(std::move(F)), Last(std::move(L)), SValue(SV), HeaderBB(H),
265 Emitted(E) {}
Anton Korobeynikov6f219132008-12-23 22:25:27 +0000266 APInt First;
267 APInt Last;
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000268 const Value *SValue;
Dan Gohman575fad32008-09-03 16:12:24 +0000269 MachineBasicBlock *HeaderBB;
270 bool Emitted;
271 };
272 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
273
274 struct BitTestCase {
Manman Rencf104462012-08-24 18:14:27 +0000275 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr,
Cong Hou1938f2e2015-11-24 08:51:23 +0000276 BranchProbability Prob):
277 Mask(M), ThisBB(T), TargetBB(Tr), ExtraProb(Prob) { }
Dan Gohman575fad32008-09-03 16:12:24 +0000278 uint64_t Mask;
Chris Lattner24576a52010-01-01 23:37:34 +0000279 MachineBasicBlock *ThisBB;
280 MachineBasicBlock *TargetBB;
Cong Hou1938f2e2015-11-24 08:51:23 +0000281 BranchProbability ExtraProb;
Dan Gohman575fad32008-09-03 16:12:24 +0000282 };
283
284 typedef SmallVector<BitTestCase, 3> BitTestInfo;
285
286 struct BitTestBlock {
Cong Hou03127702015-08-26 23:15:32 +0000287 BitTestBlock(APInt F, APInt R, const Value *SV, unsigned Rg, MVT RgVT,
288 bool E, bool CR, MachineBasicBlock *P, MachineBasicBlock *D,
Cong Hou1938f2e2015-11-24 08:51:23 +0000289 BitTestInfo C, BranchProbability Pr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000290 : First(std::move(F)), Range(std::move(R)), SValue(SV), Reg(Rg),
291 RegVT(RgVT), Emitted(E), ContiguousRange(CR), Parent(P), Default(D),
292 Cases(std::move(C)), Prob(Pr) {}
Anton Korobeynikov6f219132008-12-23 22:25:27 +0000293 APInt First;
294 APInt Range;
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000295 const Value *SValue;
Dan Gohman575fad32008-09-03 16:12:24 +0000296 unsigned Reg;
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000297 MVT RegVT;
Dan Gohman575fad32008-09-03 16:12:24 +0000298 bool Emitted;
Cong Houcd595912015-08-25 21:34:38 +0000299 bool ContiguousRange;
Dan Gohman575fad32008-09-03 16:12:24 +0000300 MachineBasicBlock *Parent;
301 MachineBasicBlock *Default;
302 BitTestInfo Cases;
Cong Hou1938f2e2015-11-24 08:51:23 +0000303 BranchProbability Prob;
304 BranchProbability DefaultProb;
Dan Gohman575fad32008-09-03 16:12:24 +0000305 };
306
Hans Wennborg0867b152015-04-23 16:45:24 +0000307 /// Check whether a range of clusters is dense enough for a jump table.
Aditya Kumar356f79d2016-09-01 23:35:26 +0000308 bool isDense(const CaseClusterVector &Clusters,
309 const SmallVectorImpl<unsigned> &TotalCases,
310 unsigned First, unsigned Last, unsigned MinDensity) const;
Hans Wennborg0867b152015-04-23 16:45:24 +0000311
312 /// Build a jump table cluster from Clusters[First..Last]. Returns false if it
313 /// decides it's not a good idea.
Aditya Kumar356f79d2016-09-01 23:35:26 +0000314 bool buildJumpTable(const CaseClusterVector &Clusters, unsigned First,
Hans Wennborg0867b152015-04-23 16:45:24 +0000315 unsigned Last, const SwitchInst *SI,
316 MachineBasicBlock *DefaultMBB, CaseCluster &JTCluster);
317
318 /// Find clusters of cases suitable for jump table lowering.
319 void findJumpTables(CaseClusterVector &Clusters, const SwitchInst *SI,
320 MachineBasicBlock *DefaultMBB);
321
322 /// Check whether the range [Low,High] fits in a machine word.
323 bool rangeFitsInWord(const APInt &Low, const APInt &High);
324
325 /// Check whether these clusters are suitable for lowering with bit tests based
326 /// on the number of destinations, comparison metric, and range.
327 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
328 const APInt &Low, const APInt &High);
329
330 /// Build a bit test cluster from Clusters[First..Last]. Returns false if it
331 /// decides it's not a good idea.
332 bool buildBitTests(CaseClusterVector &Clusters, unsigned First, unsigned Last,
333 const SwitchInst *SI, CaseCluster &BTCluster);
334
335 /// Find clusters of cases suitable for bit test lowering.
336 void findBitTestClusters(CaseClusterVector &Clusters, const SwitchInst *SI);
337
338 struct SwitchWorkListItem {
339 MachineBasicBlock *MBB;
340 CaseClusterIt FirstCluster;
341 CaseClusterIt LastCluster;
342 const ConstantInt *GE;
343 const ConstantInt *LT;
Cong Hou1938f2e2015-11-24 08:51:23 +0000344 BranchProbability DefaultProb;
Hans Wennborg0867b152015-04-23 16:45:24 +0000345 };
346 typedef SmallVector<SwitchWorkListItem, 4> SwitchWorkList;
347
Hans Wennborg6ed81cb2015-06-20 17:14:07 +0000348 /// Determine the rank by weight of CC in [First,Last]. If CC has more weight
349 /// than each cluster in the range, its rank is 0.
350 static unsigned caseClusterRank(const CaseCluster &CC, CaseClusterIt First,
351 CaseClusterIt Last);
352
Hans Wennborg0867b152015-04-23 16:45:24 +0000353 /// Emit comparison and split W into two subtrees.
354 void splitWorkItem(SwitchWorkList &WorkList, const SwitchWorkListItem &W,
355 Value *Cond, MachineBasicBlock *SwitchMBB);
356
357 /// Lower W.
358 void lowerWorkItem(SwitchWorkListItem W, Value *Cond,
359 MachineBasicBlock *SwitchMBB,
360 MachineBasicBlock *DefaultMBB);
361
362
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000363 /// A class which encapsulates all of the information needed to generate a
364 /// stack protector check and signals to isel via its state being initialized
365 /// that a stack protector needs to be generated.
366 ///
367 /// *NOTE* The following is a high level documentation of SelectionDAG Stack
368 /// Protector Generation. The reason that it is placed here is for a lack of
369 /// other good places to stick it.
370 ///
371 /// High Level Overview of SelectionDAG Stack Protector Generation:
372 ///
373 /// Previously, generation of stack protectors was done exclusively in the
374 /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated
375 /// splitting basic blocks at the IR level to create the success/failure basic
376 /// blocks in the tail of the basic block in question. As a result of this,
377 /// calls that would have qualified for the sibling call optimization were no
378 /// longer eligible for optimization since said calls were no longer right in
379 /// the "tail position" (i.e. the immediate predecessor of a ReturnInst
380 /// instruction).
381 ///
382 /// Then it was noticed that since the sibling call optimization causes the
383 /// callee to reuse the caller's stack, if we could delay the generation of
384 /// the stack protector check until later in CodeGen after the sibling call
385 /// decision was made, we get both the tail call optimization and the stack
386 /// protector check!
387 ///
388 /// A few goals in solving this problem were:
389 ///
390 /// 1. Preserve the architecture independence of stack protector generation.
391 ///
392 /// 2. Preserve the normal IR level stack protector check for platforms like
Alp Tokercf218752014-06-30 18:57:16 +0000393 /// OpenBSD for which we support platform-specific stack protector
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000394 /// generation.
395 ///
396 /// The main problem that guided the present solution is that one can not
397 /// solve this problem in an architecture independent manner at the IR level
398 /// only. This is because:
399 ///
400 /// 1. The decision on whether or not to perform a sibling call on certain
401 /// platforms (for instance i386) requires lower level information
402 /// related to available registers that can not be known at the IR level.
403 ///
404 /// 2. Even if the previous point were not true, the decision on whether to
405 /// perform a tail call is done in LowerCallTo in SelectionDAG which
406 /// occurs after the Stack Protector Pass. As a result, one would need to
407 /// put the relevant callinst into the stack protector check success
408 /// basic block (where the return inst is placed) and then move it back
409 /// later at SelectionDAG/MI time before the stack protector check if the
410 /// tail call optimization failed. The MI level option was nixed
Alp Tokercf218752014-06-30 18:57:16 +0000411 /// immediately since it would require platform-specific pattern
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000412 /// matching. The SelectionDAG level option was nixed because
413 /// SelectionDAG only processes one IR level basic block at a time
414 /// implying one could not create a DAG Combine to move the callinst.
415 ///
416 /// To get around this problem a few things were realized:
417 ///
418 /// 1. While one can not handle multiple IR level basic blocks at the
419 /// SelectionDAG Level, one can generate multiple machine basic blocks
420 /// for one IR level basic block. This is how we handle bit tests and
421 /// switches.
422 ///
423 /// 2. At the MI level, tail calls are represented via a special return
424 /// MIInst called "tcreturn". Thus if we know the basic block in which we
425 /// wish to insert the stack protector check, we get the correct behavior
426 /// by always inserting the stack protector check right before the return
427 /// statement. This is a "magical transformation" since no matter where
428 /// the stack protector check intrinsic is, we always insert the stack
429 /// protector check code at the end of the BB.
430 ///
431 /// Given the aforementioned constraints, the following solution was devised:
432 ///
433 /// 1. On platforms that do not support SelectionDAG stack protector check
434 /// generation, allow for the normal IR level stack protector check
435 /// generation to continue.
436 ///
437 /// 2. On platforms that do support SelectionDAG stack protector check
438 /// generation:
439 ///
440 /// a. Use the IR level stack protector pass to decide if a stack
441 /// protector is required/which BB we insert the stack protector check
442 /// in by reusing the logic already therein. If we wish to generate a
443 /// stack protector check in a basic block, we place a special IR
444 /// intrinsic called llvm.stackprotectorcheck right before the BB's
445 /// returninst or if there is a callinst that could potentially be
446 /// sibling call optimized, before the call inst.
447 ///
448 /// b. Then when a BB with said intrinsic is processed, we codegen the BB
449 /// normally via SelectBasicBlock. In said process, when we visit the
450 /// stack protector check, we do not actually emit anything into the
451 /// BB. Instead, we just initialize the stack protector descriptor
452 /// class (which involves stashing information/creating the success
453 /// mbbb and the failure mbb if we have not created one for this
454 /// function yet) and export the guard variable that we are going to
455 /// compare.
456 ///
457 /// c. After we finish selecting the basic block, in FinishBasicBlock if
458 /// the StackProtectorDescriptor attached to the SelectionDAGBuilder is
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000459 /// initialized, we produce the validation code with one of these
460 /// techniques:
461 /// 1) with a call to a guard check function
462 /// 2) with inlined instrumentation
463 ///
464 /// 1) We insert a call to the check function before the terminator.
465 ///
466 /// 2) We first find a splice point in the parent basic block
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000467 /// before the terminator and then splice the terminator of said basic
468 /// block into the success basic block. Then we code-gen a new tail for
469 /// the parent basic block consisting of the two loads, the comparison,
470 /// and finally two branches to the success/failure basic blocks. We
471 /// conclude by code-gening the failure basic block if we have not
472 /// code-gened it already (all stack protector checks we generate in
473 /// the same function, use the same failure basic block).
474 class StackProtectorDescriptor {
475 public:
Tim Shen00127562016-04-08 21:26:31 +0000476 StackProtectorDescriptor()
Tim Shene885d5e2016-04-19 19:40:37 +0000477 : ParentMBB(nullptr), SuccessMBB(nullptr), FailureMBB(nullptr) {}
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000478
479 /// Returns true if all fields of the stack protector descriptor are
480 /// initialized implying that we should/are ready to emit a stack protector.
481 bool shouldEmitStackProtector() const {
Tim Shen00127562016-04-08 21:26:31 +0000482 return ParentMBB && SuccessMBB && FailureMBB;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000483 }
484
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000485 bool shouldEmitFunctionBasedCheckStackProtector() const {
486 return ParentMBB && !SuccessMBB && !FailureMBB;
487 }
488
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000489 /// Initialize the stack protector descriptor structure for a new basic
490 /// block.
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000491 void initialize(const BasicBlock *BB, MachineBasicBlock *MBB,
492 bool FunctionBasedInstrumentation) {
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000493 // Make sure we are not initialized yet.
494 assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is "
495 "already initialized!");
496 ParentMBB = MBB;
Etienne Bergeron22bfa832016-06-07 20:15:35 +0000497 if (!FunctionBasedInstrumentation) {
498 SuccessMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ true);
499 FailureMBB = AddSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB);
500 }
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000501 }
502
503 /// Reset state that changes when we handle different basic blocks.
504 ///
505 /// This currently includes:
506 ///
507 /// 1. The specific basic block we are generating a
508 /// stack protector for (ParentMBB).
509 ///
510 /// 2. The successor machine basic block that will contain the tail of
511 /// parent mbb after we create the stack protector check (SuccessMBB). This
512 /// BB is visited only on stack protector check success.
513 void resetPerBBState() {
Craig Topperada08572014-04-16 04:21:27 +0000514 ParentMBB = nullptr;
515 SuccessMBB = nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000516 }
517
518 /// Reset state that only changes when we switch functions.
519 ///
520 /// This currently includes:
521 ///
522 /// 1. FailureMBB since we reuse the failure code path for all stack
523 /// protector checks created in an individual function.
524 ///
525 /// 2.The guard variable since the guard variable we are checking against is
526 /// always the same.
527 void resetPerFunctionState() {
Craig Topperada08572014-04-16 04:21:27 +0000528 FailureMBB = nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000529 }
530
531 MachineBasicBlock *getParentMBB() { return ParentMBB; }
532 MachineBasicBlock *getSuccessMBB() { return SuccessMBB; }
533 MachineBasicBlock *getFailureMBB() { return FailureMBB; }
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000534
535 private:
536 /// The basic block for which we are generating the stack protector.
537 ///
538 /// As a result of stack protector generation, we will splice the
539 /// terminators of this basic block into the successor mbb SuccessMBB and
540 /// replace it with a compare/branch to the successor mbbs
541 /// SuccessMBB/FailureMBB depending on whether or not the stack protector
542 /// was violated.
543 MachineBasicBlock *ParentMBB;
544
545 /// A basic block visited on stack protector check success that contains the
546 /// terminators of ParentMBB.
547 MachineBasicBlock *SuccessMBB;
548
549 /// This basic block visited on stack protector check failure that will
550 /// contain a call to __stack_chk_fail().
551 MachineBasicBlock *FailureMBB;
552
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000553 /// Add a successor machine basic block to ParentMBB. If the successor mbb
554 /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic
Akira Hatanakab9991a22014-12-01 04:27:03 +0000555 /// block will be created. Assign a large weight if IsLikely is true.
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000556 MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB,
557 MachineBasicBlock *ParentMBB,
Akira Hatanakab9991a22014-12-01 04:27:03 +0000558 bool IsLikely,
Craig Topperada08572014-04-16 04:21:27 +0000559 MachineBasicBlock *SuccMBB = nullptr);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000560 };
561
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000562private:
Dan Gohmanc3349602010-04-19 19:05:59 +0000563 const TargetMachine &TM;
Bill Wendlinga3cd3502013-06-19 21:36:55 +0000564public:
Nico Rieckb5262d62014-01-12 14:09:17 +0000565 /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
566 /// nodes without a corresponding SDNode.
567 static const unsigned LowestSDNodeOrder = 1;
568
Dan Gohman575fad32008-09-03 16:12:24 +0000569 SelectionDAG &DAG;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000570 const DataLayout *DL;
Dan Gohman575fad32008-09-03 16:12:24 +0000571 AliasAnalysis *AA;
Owen Andersonbb15fec2011-12-08 22:15:21 +0000572 const TargetLibraryInfo *LibInfo;
Dan Gohman575fad32008-09-03 16:12:24 +0000573
574 /// SwitchCases - Vector of CaseBlock structures used to communicate
575 /// SwitchInst code generation information.
576 std::vector<CaseBlock> SwitchCases;
577 /// JTCases - Vector of JumpTable structures used to communicate
578 /// SwitchInst code generation information.
579 std::vector<JumpTableBlock> JTCases;
580 /// BitTestCases - Vector of BitTestBlock structures used to communicate
581 /// SwitchInst code generation information.
582 std::vector<BitTestBlock> BitTestCases;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000583 /// A StackProtectorDescriptor structure used to communicate stack protector
584 /// information in between SelectBasicBlock and FinishBasicBlock.
585 StackProtectorDescriptor SPDescriptor;
Evan Cheng270d0f92009-09-18 21:02:19 +0000586
Dan Gohman575fad32008-09-03 16:12:24 +0000587 // Emit PHI-node-operand constants only once even if used by multiple
588 // PHI nodes.
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000589 DenseMap<const Constant *, unsigned> ConstantsOut;
Dan Gohman575fad32008-09-03 16:12:24 +0000590
591 /// FuncInfo - Information about the function as a whole.
592 ///
593 FunctionLoweringInfo &FuncInfo;
Bill Wendling19e0a5b2009-02-19 21:12:54 +0000594
Dan Gohman575fad32008-09-03 16:12:24 +0000595 /// GFI - Garbage collection metadata for the function.
596 GCFunctionInfo *GFI;
597
Bill Wendling267f3232011-10-05 22:24:35 +0000598 /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
599 DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
Bill Wendling3d11aa72011-10-04 22:00:35 +0000600
Dan Gohmanf9bbcd12009-08-05 01:29:28 +0000601 /// HasTailCall - This is set to true if a call in the current
602 /// block has been translated as a tail call. In this case,
603 /// no subsequent DAG nodes should be created.
604 ///
605 bool HasTailCall;
606
Owen Anderson53a52212009-07-13 04:09:18 +0000607 LLVMContext *Context;
608
Dan Gohmanc3349602010-04-19 19:05:59 +0000609 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000610 CodeGenOpt::Level ol)
Craig Topperada08572014-04-16 04:21:27 +0000611 : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()),
Benjamin Kramerbacc7ba2015-10-15 17:54:06 +0000612 DAG(dag), FuncInfo(funcinfo),
Richard Smith3fb20472012-08-22 00:42:39 +0000613 HasTailCall(false) {
Dan Gohman575fad32008-09-03 16:12:24 +0000614 }
615
Owen Andersonbb15fec2011-12-08 22:15:21 +0000616 void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
617 const TargetLibraryInfo *li);
Dan Gohman575fad32008-09-03 16:12:24 +0000618
Dan Gohmanf5cca352010-04-14 18:24:06 +0000619 /// clear - Clear out the current SelectionDAG and the associated
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000620 /// state and prepare this SelectionDAGBuilder object to be used
Dan Gohman575fad32008-09-03 16:12:24 +0000621 /// for a new block. This doesn't clear out information about
622 /// additional blocks that are needed to complete switch lowering
623 /// or PHI node updating; that information is cleared out as it is
624 /// consumed.
625 void clear();
626
Devang Patel799288382011-05-23 17:44:13 +0000627 /// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerbde91762012-06-02 10:20:22 +0000628 /// map. This function is separated from the clear so that debug
Devang Patel799288382011-05-23 17:44:13 +0000629 /// information that is dangling in a basic block can be properly
630 /// resolved in a different basic block. This allows the
631 /// SelectionDAG to resolve dangling debug information attached
632 /// to PHI nodes.
633 void clearDanglingDebugInfo();
634
Dan Gohman575fad32008-09-03 16:12:24 +0000635 /// getRoot - Return the current virtual root of the Selection DAG,
636 /// flushing any PendingLoad items. This must be done before emitting
637 /// a store or any other node that may need to be ordered after any
638 /// prior load instructions.
639 ///
640 SDValue getRoot();
641
642 /// getControlRoot - Similar to getRoot, but instead of flushing all the
643 /// PendingLoad items, flush all the PendingExports items. It is necessary
644 /// to do this before emitting a terminator instruction.
645 ///
646 SDValue getControlRoot();
647
Andrew Trick175143b2013-05-25 02:20:36 +0000648 SDLoc getCurSDLoc() const {
Andrew Trick175143b2013-05-25 02:20:36 +0000649 return SDLoc(CurInst, SDNodeOrder);
650 }
651
652 DebugLoc getCurDebugLoc() const {
653 return CurInst ? CurInst->getDebugLoc() : DebugLoc();
654 }
Devang Patelf3292b22011-02-21 23:21:26 +0000655
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000656 void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
Dan Gohman575fad32008-09-03 16:12:24 +0000657
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000658 void visit(const Instruction &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000659
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000660 void visit(unsigned Opcode, const User &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000661
Igor Laevsky85f7f722015-03-10 16:26:48 +0000662 /// getCopyFromRegs - If there was virtual register allocated for the value V
663 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
664 SDValue getCopyFromRegs(const Value *V, Type *Ty);
665
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000666 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
667 // generate the debug data structures now that we've seen its definition.
668 void resolveDanglingDebugInfo(const Value *V, SDValue Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000669 SDValue getValue(const Value *V);
Elena Demikhovsky584ce372015-04-28 07:57:37 +0000670 bool findValue(const Value *V) const;
671
Dan Gohmand4322232010-07-01 01:59:43 +0000672 SDValue getNonRegisterValue(const Value *V);
673 SDValue getValueImpl(const Value *V);
Dan Gohman575fad32008-09-03 16:12:24 +0000674
675 void setValue(const Value *V, SDValue NewN) {
676 SDValue &N = NodeMap[V];
Craig Topperada08572014-04-16 04:21:27 +0000677 assert(!N.getNode() && "Already set a value for this node!");
Dan Gohman575fad32008-09-03 16:12:24 +0000678 N = NewN;
679 }
Andrew Trickd4d1d9c2013-10-31 17:18:07 +0000680
Devang Patelb0c76392010-06-01 19:59:01 +0000681 void setUnusedArgValue(const Value *V, SDValue NewN) {
682 SDValue &N = UnusedArgNodeMap[V];
Craig Topperada08572014-04-16 04:21:27 +0000683 assert(!N.getNode() && "Already set a value for this node!");
Devang Patelb0c76392010-06-01 19:59:01 +0000684 N = NewN;
685 }
Dan Gohman575fad32008-09-03 16:12:24 +0000686
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000687 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
Dan Gohman575fad32008-09-03 16:12:24 +0000688 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
Pete Cooper69234612015-07-15 01:31:26 +0000689 MachineBasicBlock *SwitchBB,
Cong Hou1938f2e2015-11-24 08:51:23 +0000690 Instruction::BinaryOps Opc, BranchProbability TW,
Geoff Berry92a286a2017-01-24 16:36:07 +0000691 BranchProbability FW, bool InvertCond);
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000692 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
Dan Gohmand01ddb52008-10-17 21:16:08 +0000693 MachineBasicBlock *FBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +0000694 MachineBasicBlock *CurBB,
Manman Ren4ece7452014-01-31 00:42:44 +0000695 MachineBasicBlock *SwitchBB,
Geoff Berry92a286a2017-01-24 16:36:07 +0000696 BranchProbability TW, BranchProbability FW,
697 bool InvertCond);
Dan Gohman575fad32008-09-03 16:12:24 +0000698 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000699 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
700 void CopyToExportRegsIfNeeded(const Value *V);
701 void ExportFromCurrentBlock(const Value *V);
702 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000703 const BasicBlock *EHPadBB = nullptr);
Dan Gohman575fad32008-09-03 16:12:24 +0000704
Matt Arsenault2bba7792016-02-08 16:28:19 +0000705 // Lower range metadata from 0 to N to assert zext to an integer of nearest
706 // floor power of two.
707 SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I,
708 SDValue Op);
709
Sanjoy Das19c61592016-03-16 20:49:31 +0000710 void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI,
711 ImmutableCallSite CS, unsigned ArgIdx,
712 unsigned NumArgs, SDValue Callee,
713 Type *ReturnTy, bool IsPatchPoint);
714
715 std::pair<SDValue, SDValue>
716 lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
717 const BasicBlock *EHPadBB = nullptr);
Andrew Trick74f4c742013-10-31 17:18:24 +0000718
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +0000719 /// UpdateSplitBlock - When an MBB was split during scheduling, update the
Alp Toker798060e2014-01-11 14:01:43 +0000720 /// references that need to refer to the last resulting block.
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +0000721 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
722
Sanjoy Das70697ff2016-03-16 23:08:00 +0000723 /// Describes a gc.statepoint or a gc.statepoint like thing for the purposes
Sanjoy Dasa5b29722016-03-23 02:28:35 +0000724 /// of lowering into a STATEPOINT node.
Sanjoy Das70697ff2016-03-16 23:08:00 +0000725 struct StatepointLoweringInfo {
726 /// Bases[i] is the base pointer for Ptrs[i]. Together they denote the set
727 /// of gc pointers this STATEPOINT has to relocate.
Sanjoy Dase58ca592016-03-23 02:24:07 +0000728 SmallVector<const Value *, 16> Bases;
729 SmallVector<const Value *, 16> Ptrs;
Sanjoy Das70697ff2016-03-16 23:08:00 +0000730
731 /// The set of gc.relocate calls associated with this gc.statepoint.
Sanjoy Dase58ca592016-03-23 02:24:07 +0000732 SmallVector<const GCRelocateInst *, 16> GCRelocates;
Sanjoy Das70697ff2016-03-16 23:08:00 +0000733
734 /// The full list of gc arguments to the gc.statepoint being lowered.
735 ArrayRef<const Use> GCArgs;
736
737 /// The gc.statepoint instruction.
738 const Instruction *StatepointInstr = nullptr;
739
740 /// The list of gc transition arguments present in the gc.statepoint being
741 /// lowered.
742 ArrayRef<const Use> GCTransitionArgs;
743
744 /// The ID that the resulting STATEPOINT instruction has to report.
745 unsigned ID = -1;
746
747 /// Information regarding the underlying call instruction.
748 TargetLowering::CallLoweringInfo CLI;
749
750 /// The deoptimization state associated with this gc.statepoint call, if
751 /// any.
752 ArrayRef<const Use> DeoptState;
753
754 /// Flags associated with the meta arguments being lowered.
755 uint64_t StatepointFlags = -1;
756
757 /// The number of patchable bytes the call needs to get lowered into.
758 unsigned NumPatchBytes = -1;
759
760 /// The exception handling unwind destination, in case this represents an
761 /// invoke of gc.statepoint.
762 const BasicBlock *EHPadBB = nullptr;
763
764 explicit StatepointLoweringInfo(SelectionDAG &DAG) : CLI(DAG) {}
765 };
766
767 /// Lower \p SLI into a STATEPOINT instruction.
Sanjoy Das38bfc222016-03-22 00:59:13 +0000768 SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SLI);
Sanjoy Das70697ff2016-03-16 23:08:00 +0000769
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000770 // This function is responsible for the whole statepoint lowering process.
Igor Laevsky85f7f722015-03-10 16:26:48 +0000771 // It uniformly handles invoke and call statepoints.
772 void LowerStatepoint(ImmutableStatepoint Statepoint,
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000773 const BasicBlock *EHPadBB = nullptr);
Sanjoy Das38bfc222016-03-22 00:59:13 +0000774
775 void LowerCallSiteWithDeoptBundle(ImmutableCallSite CS, SDValue Callee,
776 const BasicBlock *EHPadBB);
777
Sanjoy Dasdf9ae702016-03-24 20:23:29 +0000778 void LowerDeoptimizeCall(const CallInst *CI);
Sanjoy Das65a60672016-04-06 01:33:49 +0000779 void LowerDeoptimizingReturn();
Sanjoy Dasdf9ae702016-03-24 20:23:29 +0000780
Sanjoy Dasfd3eaa82016-03-24 22:51:49 +0000781 void LowerCallSiteWithDeoptBundleImpl(ImmutableCallSite CS, SDValue Callee,
782 const BasicBlock *EHPadBB,
Sanjoy Das65a60672016-04-06 01:33:49 +0000783 bool VarArgDisallowed,
784 bool ForceVoidReturnTy);
Sanjoy Dasfd3eaa82016-03-24 22:51:49 +0000785
Dan Gohman575fad32008-09-03 16:12:24 +0000786private:
787 // Terminator instructions.
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000788 void visitRet(const ReturnInst &I);
789 void visitBr(const BranchInst &I);
790 void visitSwitch(const SwitchInst &I);
791 void visitIndirectBr(const IndirectBrInst &I);
Yaron Kerend7ba46b2014-04-19 13:47:43 +0000792 void visitUnreachable(const UnreachableInst &I);
David Majnemer654e1302015-07-31 17:58:14 +0000793 void visitCleanupRet(const CleanupReturnInst &I);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000794 void visitCatchSwitch(const CatchSwitchInst &I);
David Majnemer654e1302015-07-31 17:58:14 +0000795 void visitCatchRet(const CatchReturnInst &I);
796 void visitCatchPad(const CatchPadInst &I);
David Majnemer654e1302015-07-31 17:58:14 +0000797 void visitCleanupPad(const CleanupPadInst &CPI);
Dan Gohman575fad32008-09-03 16:12:24 +0000798
Cong Hou1938f2e2015-11-24 08:51:23 +0000799 BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
800 const MachineBasicBlock *Dst) const;
801 void addSuccessorWithProb(
802 MachineBasicBlock *Src, MachineBasicBlock *Dst,
803 BranchProbability Prob = BranchProbability::getUnknown());
804
Dan Gohman575fad32008-09-03 16:12:24 +0000805public:
Dan Gohman7c0303a2010-04-19 22:41:47 +0000806 void visitSwitchCase(CaseBlock &CB,
807 MachineBasicBlock *SwitchBB);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +0000808 void visitSPDescriptorParent(StackProtectorDescriptor &SPD,
809 MachineBasicBlock *ParentBB);
810 void visitSPDescriptorFailure(StackProtectorDescriptor &SPD);
Dan Gohman7c0303a2010-04-19 22:41:47 +0000811 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
Evan Chengac730dd2011-01-06 01:02:44 +0000812 void visitBitTestCase(BitTestBlock &BB,
813 MachineBasicBlock* NextMBB,
Cong Hou1938f2e2015-11-24 08:51:23 +0000814 BranchProbability BranchProbToNext,
Dan Gohman575fad32008-09-03 16:12:24 +0000815 unsigned Reg,
Dan Gohman7c0303a2010-04-19 22:41:47 +0000816 BitTestCase &B,
817 MachineBasicBlock *SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +0000818 void visitJumpTable(JumpTable &JT);
Dan Gohman7c0303a2010-04-19 22:41:47 +0000819 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
820 MachineBasicBlock *SwitchBB);
Andrew Trickd4d1d9c2013-10-31 17:18:07 +0000821
Dan Gohman575fad32008-09-03 16:12:24 +0000822private:
823 // These all get lowered before this pass.
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000824 void visitInvoke(const InvokeInst &I);
Bill Wendlingf891bf82011-07-31 06:30:59 +0000825 void visitResume(const ResumeInst &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000826
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000827 void visitBinary(const User &I, unsigned OpCode);
828 void visitShift(const User &I, unsigned Opcode);
829 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
830 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
831 void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
832 void visitFSub(const User &I);
833 void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
834 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
835 void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
836 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
837 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
838 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
Benjamin Kramer9960a252011-07-08 10:31:30 +0000839 void visitSDiv(const User &I);
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000840 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
841 void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
842 void visitOr (const User &I) { visitBinary(I, ISD::OR); }
843 void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
844 void visitShl (const User &I) { visitShift(I, ISD::SHL); }
845 void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
846 void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
847 void visitICmp(const User &I);
848 void visitFCmp(const User &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000849 // Visit the conversion instructions
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000850 void visitTrunc(const User &I);
851 void visitZExt(const User &I);
852 void visitSExt(const User &I);
853 void visitFPTrunc(const User &I);
854 void visitFPExt(const User &I);
855 void visitFPToUI(const User &I);
856 void visitFPToSI(const User &I);
857 void visitUIToFP(const User &I);
858 void visitSIToFP(const User &I);
859 void visitPtrToInt(const User &I);
860 void visitIntToPtr(const User &I);
861 void visitBitCast(const User &I);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000862 void visitAddrSpaceCast(const User &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000863
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000864 void visitExtractElement(const User &I);
865 void visitInsertElement(const User &I);
866 void visitShuffleVector(const User &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000867
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000868 void visitExtractValue(const ExtractValueInst &I);
869 void visitInsertValue(const InsertValueInst &I);
Bill Wendlingfae14752011-08-12 20:24:12 +0000870 void visitLandingPad(const LandingPadInst &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000871
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000872 void visitGetElementPtr(const User &I);
873 void visitSelect(const User &I);
Dan Gohman575fad32008-09-03 16:12:24 +0000874
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000875 void visitAlloca(const AllocaInst &I);
876 void visitLoad(const LoadInst &I);
877 void visitStore(const StoreInst &I);
Elena Demikhovskycaaceef2016-11-03 03:23:55 +0000878 void visitMaskedLoad(const CallInst &I, bool IsExpanding = false);
879 void visitMaskedStore(const CallInst &I, bool IsCompressing = false);
Elena Demikhovsky584ce372015-04-28 07:57:37 +0000880 void visitMaskedGather(const CallInst &I);
881 void visitMaskedScatter(const CallInst &I);
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000882 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
883 void visitAtomicRMW(const AtomicRMWInst &I);
Eli Friedmanfee02c62011-07-25 23:16:38 +0000884 void visitFence(const FenceInst &I);
Dan Gohmanf41ad472010-04-20 15:00:41 +0000885 void visitPHI(const PHINode &I);
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000886 void visitCall(const CallInst &I);
887 bool visitMemCmpCall(const CallInst &I);
Andrew Kaylorb99d1cc2016-07-29 18:23:18 +0000888 bool visitMemPCpyCall(const CallInst &I);
Richard Sandiford6f6d5512013-08-20 09:38:48 +0000889 bool visitMemChrCall(const CallInst &I);
Richard Sandifordbb83a502013-08-16 11:29:37 +0000890 bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
Richard Sandifordca232712013-08-16 11:21:54 +0000891 bool visitStrCmpCall(const CallInst &I);
Richard Sandiford0dec06a2013-08-16 11:41:43 +0000892 bool visitStrLenCall(const CallInst &I);
893 bool visitStrNLenCall(const CallInst &I);
Bob Wilson874886c2012-08-03 23:29:17 +0000894 bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
Matt Arsenault7c936902014-10-21 23:01:01 +0000895 bool visitBinaryFloatCall(const CallInst &I, unsigned Opcode);
Eli Friedman342e8df2011-08-24 20:50:09 +0000896 void visitAtomicLoad(const LoadInst &I);
897 void visitAtomicStore(const StoreInst &I);
Manman Rene221a872016-04-05 18:13:16 +0000898 void visitLoadFromSwiftError(const LoadInst &I);
899 void visitStoreToSwiftError(const StoreInst &I);
Eli Friedman342e8df2011-08-24 20:50:09 +0000900
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000901 void visitInlineAsm(ImmutableCallSite CS);
902 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
903 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
Dan Gohman575fad32008-09-03 16:12:24 +0000904
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000905 void visitVAStart(const CallInst &I);
906 void visitVAArg(const VAArgInst &I);
907 void visitVAEnd(const CallInst &I);
908 void visitVACopy(const CallInst &I);
Andrew Trick74f4c742013-10-31 17:18:24 +0000909 void visitStackmap(const CallInst &I);
Juergen Ributzkaad2363f2014-10-17 17:39:00 +0000910 void visitPatchpoint(ImmutableCallSite CS,
Reid Kleckner51189f0a2015-09-08 23:28:38 +0000911 const BasicBlock *EHPadBB = nullptr);
Dan Gohman575fad32008-09-03 16:12:24 +0000912
Sanjoy Das3a020192016-03-17 00:47:14 +0000913 // These two are implemented in StatepointLowering.cpp
Manuel Jacob83eefa62016-01-05 04:03:00 +0000914 void visitGCRelocate(const GCRelocateInst &I);
Philip Reames92d1f0c2016-04-12 18:05:10 +0000915 void visitGCResult(const GCResultInst &I);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000916
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000917 void visitUserOp1(const Instruction &I) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000918 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
Dan Gohman575fad32008-09-03 16:12:24 +0000919 }
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000920 void visitUserOp2(const Instruction &I) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000921 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
Dan Gohman575fad32008-09-03 16:12:24 +0000922 }
Dan Gohman5b43aa02010-04-22 20:55:53 +0000923
Richard Sandiforde3827752013-08-16 10:55:47 +0000924 void processIntegerCallValue(const Instruction &I,
925 SDValue Value, bool IsSigned);
926
Dan Gohman5b43aa02010-04-22 20:55:53 +0000927 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
Evan Cheng6e822452010-04-28 23:08:54 +0000928
Renato Golin38ed8022016-05-17 19:52:01 +0000929 void emitInlineAsmError(ImmutableCallSite CS, const Twine &Message);
930
Devang Patel32a72ab2010-08-25 20:41:24 +0000931 /// EmitFuncArgumentDbgValue - If V is an function argument then create
Andrew Trickd4d1d9c2013-10-31 17:18:07 +0000932 /// corresponding DBG_VALUE machine instruction for it now. At the end of
Devang Patel32a72ab2010-08-25 20:41:24 +0000933 /// instruction selection, they will be inserted to the entry BB.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000934 bool EmitFuncArgumentDbgValue(const Value *V, DILocalVariable *Variable,
935 DIExpression *Expr, DILocation *DL,
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000936 int64_t Offset, bool IsIndirect,
937 const SDValue &N);
Hans Wennborgb4db1422015-03-19 20:41:48 +0000938
939 /// Return the next block after MBB, or nullptr if there is none.
940 MachineBasicBlock *NextBlock(MachineBasicBlock *MBB);
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +0000941
942 /// Update the DAG and DAG builder with the relevant information after
943 /// a new root node has been created which could be a tail call.
944 void updateDAGForMaybeTailCall(SDValue MaybeTC);
Wolfgang Piebdfad9b22016-08-15 18:18:26 +0000945
946 /// Return the appropriate SDDbgValue based on N.
947 SDDbgValue *getDbgValue(SDValue N, DILocalVariable *Variable,
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000948 DIExpression *Expr, int64_t Offset,
949 const DebugLoc &dl, unsigned DbgSDNodeOrder);
Dan Gohman575fad32008-09-03 16:12:24 +0000950};
951
Sanjoy Das3936a972015-05-05 23:06:54 +0000952/// RegsForValue - This struct represents the registers (physical or virtual)
953/// that a particular set of values is assigned, and the type information about
954/// the value. The most common situation is to represent one value at a time,
955/// but struct or array values are handled element-wise as multiple values. The
956/// splitting of aggregates is performed recursively, so that we never have
957/// aggregate-typed registers. The values at this point do not necessarily have
958/// legal types, so each value may require one or more registers of some legal
959/// type.
960///
961struct RegsForValue {
962 /// ValueVTs - The value types of the values, which may not be legal, and
963 /// may need be promoted or synthesized from one or more registers.
964 ///
965 SmallVector<EVT, 4> ValueVTs;
966
967 /// RegVTs - The value types of the registers. This is the same size as
968 /// ValueVTs and it records, for each value, what the type of the assigned
969 /// register or registers are. (Individual values are never synthesized
970 /// from more than one type of register.)
971 ///
972 /// With virtual registers, the contents of RegVTs is redundant with TLI's
973 /// getRegisterType member function, however when with physical registers
974 /// it is necessary to have a separate record of the types.
975 ///
976 SmallVector<MVT, 4> RegVTs;
977
978 /// Regs - This list holds the registers assigned to the values.
979 /// Each legal or promoted value requires one register, and each
980 /// expanded value requires multiple registers.
981 ///
982 SmallVector<unsigned, 4> Regs;
983
984 RegsForValue();
985
986 RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt, EVT valuevt);
987
Mehdi Amini56228da2015-07-09 01:57:34 +0000988 RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
989 const DataLayout &DL, unsigned Reg, Type *Ty);
Sanjoy Das3936a972015-05-05 23:06:54 +0000990
991 /// append - Add the specified values to this one.
992 void append(const RegsForValue &RHS) {
993 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
994 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
995 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
996 }
997
998 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
999 /// this value and returns the result as a ValueVTs value. This uses
1000 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1001 /// If the Flag pointer is NULL, no flag is used.
1002 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001003 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
Sanjoy Das3936a972015-05-05 23:06:54 +00001004 const Value *V = nullptr) const;
1005
Sanjoy Das1194d1e72015-05-05 23:06:57 +00001006 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the specified
1007 /// value into the registers specified by this object. This uses Chain/Flag
1008 /// as the input and updates them for the output Chain/Flag. If the Flag
1009 /// pointer is nullptr, no flag is used. If V is not nullptr, then it is used
1010 /// in printing better diagnostic messages on error.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001011 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl,
1012 SDValue &Chain, SDValue *Flag, const Value *V = nullptr,
1013 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
Sanjoy Das3936a972015-05-05 23:06:54 +00001014
1015 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1016 /// operand list. This adds the code marker, matching input operand index
1017 /// (if applicable), and includes the number of values added into it.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001018 void AddInlineAsmOperands(unsigned Kind, bool HasMatching,
1019 unsigned MatchingIdx, const SDLoc &dl,
1020 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Sanjoy Das3936a972015-05-05 23:06:54 +00001021};
1022
Dan Gohman575fad32008-09-03 16:12:24 +00001023} // end namespace llvm
1024
1025#endif