blob: f0fae92af6de29990c3fd0fb42e16d76460dc83b [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceCfgNode.cpp - Basic block (node) implementation -----===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
11/// This file implements the CfgNode class, including the complexities
12/// of instruction insertion and in-edge calculation.
13///
Jim Stichnothf7c9a142014-04-29 10:52:43 -070014//===----------------------------------------------------------------------===//
15
John Porto67f8de92015-06-25 10:14:17 -070016#include "IceCfgNode.h"
17
John Portoaff4ccf2015-06-10 16:35:06 -070018#include "IceAssembler.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070019#include "IceCfg.h"
John Portof8b4cc82015-06-09 18:06:19 -070020#include "IceGlobalInits.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070021#include "IceInst.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070022#include "IceLiveness.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070023#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070024#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070025
26namespace Ice {
27
Jim Stichnoth668a7a32014-12-10 15:32:25 -080028CfgNode::CfgNode(Cfg *Func, SizeT LabelNumber)
Jim Stichnotheafb56c2015-06-22 10:35:22 -070029 : Func(Func), Number(LabelNumber) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070030
31// Returns the name the node was created with. If no name was given,
32// it synthesizes a (hopefully) unique name.
33IceString CfgNode::getName() const {
Jim Stichnoth668a7a32014-12-10 15:32:25 -080034 if (NameIndex >= 0)
Jim Stichnoth9a04c072014-12-11 15:51:42 -080035 return Func->getIdentifierName(NameIndex);
Jim Stichnoth088b2be2014-10-23 12:02:08 -070036 return "__" + std::to_string(getIndex());
Jim Stichnothf7c9a142014-04-29 10:52:43 -070037}
38
39// Adds an instruction to either the Phi list or the regular
40// instruction list. Validates that all Phis are added before all
41// regular instructions.
42void CfgNode::appendInst(Inst *Inst) {
Jim Stichnoth47752552014-10-13 17:15:08 -070043 ++InstCountEstimate;
Jim Stichnothf7c9a142014-04-29 10:52:43 -070044 if (InstPhi *Phi = llvm::dyn_cast<InstPhi>(Inst)) {
45 if (!Insts.empty()) {
46 Func->setError("Phi instruction added to the middle of a block");
47 return;
48 }
49 Phis.push_back(Phi);
50 } else {
51 Insts.push_back(Inst);
52 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -070053}
54
Jim Stichnothd97c7df2014-06-04 11:57:08 -070055// Renumbers the non-deleted instructions in the node. This needs to
56// be done in preparation for live range analysis. The instruction
57// numbers in a block must be monotonically increasing. The range of
58// instruction numbers in a block, from lowest to highest, must not
59// overlap with the range of any other block.
60void CfgNode::renumberInstructions() {
Jim Stichnoth47752552014-10-13 17:15:08 -070061 InstNumberT FirstNumber = Func->getNextInstNumber();
Jim Stichnoth29841e82014-12-23 12:26:24 -080062 for (Inst &I : Phis)
63 I.renumber(Func);
64 for (Inst &I : Insts)
65 I.renumber(Func);
Jim Stichnoth47752552014-10-13 17:15:08 -070066 InstCountEstimate = Func->getNextInstNumber() - FirstNumber;
Jim Stichnothd97c7df2014-06-04 11:57:08 -070067}
68
Jim Stichnoth088b2be2014-10-23 12:02:08 -070069// When a node is created, the OutEdges are immediately known, but the
Jim Stichnothf7c9a142014-04-29 10:52:43 -070070// InEdges have to be built up incrementally. After the CFG has been
71// constructed, the computePredecessors() pass finalizes it by
72// creating the InEdges list.
73void CfgNode::computePredecessors() {
Jim Stichnothf44f3712014-10-01 14:05:51 -070074 for (CfgNode *Succ : OutEdges)
75 Succ->InEdges.push_back(this);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070076}
77
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -070078void CfgNode::computeSuccessors() {
79 OutEdges = Insts.rbegin()->getTerminatorEdges();
80}
81
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070082// This does part 1 of Phi lowering, by creating a new dest variable
83// for each Phi instruction, replacing the Phi instruction's dest with
84// that variable, and adding an explicit assignment of the old dest to
85// the new dest. For example,
86// a=phi(...)
87// changes to
88// "a_phi=phi(...); a=a_phi".
89//
90// This is in preparation for part 2 which deletes the Phi
91// instructions and appends assignment instructions to predecessor
92// blocks. Note that this transformation preserves SSA form.
93void CfgNode::placePhiLoads() {
Jim Stichnoth29841e82014-12-23 12:26:24 -080094 for (Inst &I : Phis) {
95 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -080096 Insts.insert(Insts.begin(), Phi->lower(Func));
97 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070098}
99
100// This does part 2 of Phi lowering. For each Phi instruction at each
101// out-edge, create a corresponding assignment instruction, and add
102// all the assignments near the end of this block. They need to be
103// added before any branch instruction, and also if the block ends
104// with a compare instruction followed by a branch instruction that we
105// may want to fuse, it's better to insert the new assignments before
Jan Voungc820ddf2014-07-29 14:38:51 -0700106// the compare instruction. The tryOptimizedCmpxchgCmpBr() method
107// assumes this ordering of instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700108//
109// Note that this transformation takes the Phi dest variables out of
110// SSA form, as there may be assignments to the dest variable in
111// multiple blocks.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700112void CfgNode::placePhiStores() {
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700113 // Find the insertion point.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700114 InstList::iterator InsertionPoint = Insts.end();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700115 // Every block must end in a terminator instruction, and therefore
116 // must have at least one instruction, so it's valid to decrement
117 // InsertionPoint (but assert just in case).
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700118 assert(InsertionPoint != Insts.begin());
119 --InsertionPoint;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700120 // Confirm that InsertionPoint is a terminator instruction. Calling
121 // getTerminatorEdges() on a non-terminator instruction will cause
122 // an llvm_unreachable().
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800123 (void)InsertionPoint->getTerminatorEdges();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700124 // SafeInsertionPoint is always immediately before the terminator
125 // instruction. If the block ends in a compare and conditional
126 // branch, it's better to place the Phi store before the compare so
127 // as not to interfere with compare/branch fusing. However, if the
128 // compare instruction's dest operand is the same as the new
129 // assignment statement's source operand, this can't be done due to
130 // data dependences, so we need to fall back to the
131 // SafeInsertionPoint. To illustrate:
132 // ; <label>:95
133 // %97 = load i8* %96, align 1
134 // %98 = icmp ne i8 %97, 0
135 // br i1 %98, label %99, label %2132
136 // ; <label>:99
137 // %100 = phi i8 [ %97, %95 ], [ %110, %108 ]
138 // %101 = phi i1 [ %98, %95 ], [ %111, %108 ]
139 // would be Phi-lowered as:
140 // ; <label>:95
141 // %97 = load i8* %96, align 1
142 // %100_phi = %97 ; can be at InsertionPoint
143 // %98 = icmp ne i8 %97, 0
144 // %101_phi = %98 ; must be at SafeInsertionPoint
145 // br i1 %98, label %99, label %2132
146 // ; <label>:99
147 // %100 = %100_phi
148 // %101 = %101_phi
149 //
150 // TODO(stichnot): It may be possible to bypass this whole
151 // SafeInsertionPoint mechanism. If a source basic block ends in a
152 // conditional branch:
153 // labelSource:
154 // ...
155 // br i1 %foo, label %labelTrue, label %labelFalse
156 // and a branch target has a Phi involving the branch operand:
157 // labelTrue:
158 // %bar = phi i1 [ %foo, %labelSource ], ...
159 // then we actually know the constant i1 value of the Phi operand:
160 // labelTrue:
161 // %bar = phi i1 [ true, %labelSource ], ...
162 // It seems that this optimization should be done by clang or opt,
163 // but we could also do it here.
164 InstList::iterator SafeInsertionPoint = InsertionPoint;
165 // Keep track of the dest variable of a compare instruction, so that
166 // we insert the new instruction at the SafeInsertionPoint if the
167 // compare's dest matches the Phi-lowered assignment's source.
Jim Stichnothae953202014-12-20 06:17:49 -0800168 Variable *CmpInstDest = nullptr;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700169 // If the current insertion point is at a conditional branch
170 // instruction, and the previous instruction is a compare
171 // instruction, then we move the insertion point before the compare
172 // instruction so as not to interfere with compare/branch fusing.
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800173 if (InstBr *Branch = llvm::dyn_cast<InstBr>(InsertionPoint)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700174 if (!Branch->isUnconditional()) {
175 if (InsertionPoint != Insts.begin()) {
176 --InsertionPoint;
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800177 if (llvm::isa<InstIcmp>(InsertionPoint) ||
178 llvm::isa<InstFcmp>(InsertionPoint)) {
179 CmpInstDest = InsertionPoint->getDest();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700180 } else {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700181 ++InsertionPoint;
182 }
183 }
184 }
185 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700186
187 // Consider every out-edge.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700188 for (CfgNode *Succ : OutEdges) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700189 // Consider every Phi instruction at the out-edge.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800190 for (Inst &I : Succ->Phis) {
191 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800192 Operand *Operand = Phi->getOperandForTarget(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700193 assert(Operand);
Jim Stichnoth29841e82014-12-23 12:26:24 -0800194 Variable *Dest = I.getDest();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700195 assert(Dest);
196 InstAssign *NewInst = InstAssign::create(Func, Dest, Operand);
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700197 if (CmpInstDest == Operand)
198 Insts.insert(SafeInsertionPoint, NewInst);
199 else
200 Insts.insert(InsertionPoint, NewInst);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700201 }
202 }
203}
204
205// Deletes the phi instructions after the loads and stores are placed.
206void CfgNode::deletePhis() {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800207 for (Inst &I : Phis)
208 I.setDeleted();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700209}
210
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700211// Splits the edge from Pred to this node by creating a new node and
212// hooking up the in and out edges appropriately. (The EdgeIndex
213// parameter is only used to make the new node's name unique when
214// there are multiple edges between the same pair of nodes.) The new
215// node's instruction list is initialized to the empty list, with no
Andrew Scull87f80c12015-07-20 10:19:16 -0700216// terminator instruction. There must not be multiple edges from Pred
217// to this node so all Inst::getTerminatorEdges implementations must
218// not contain duplicates.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700219CfgNode *CfgNode::splitIncomingEdge(CfgNode *Pred, SizeT EdgeIndex) {
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800220 CfgNode *NewNode = Func->makeNode();
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700221 if (BuildDefs::dump())
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800222 NewNode->setName("split_" + Pred->getName() + "_" + getName() + "_" +
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700223 std::to_string(EdgeIndex));
224 // The new node is added to the end of the node list, and will later
225 // need to be sorted into a reasonable topological order.
226 NewNode->setNeedsPlacement(true);
227 // Repoint Pred's out-edge.
228 bool Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700229 for (CfgNode *&I : Pred->OutEdges) {
230 if (I == this) {
231 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700232 NewNode->InEdges.push_back(Pred);
233 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700234 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700235 }
236 }
237 assert(Found);
238 // Repoint this node's in-edge.
239 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700240 for (CfgNode *&I : InEdges) {
241 if (I == Pred) {
242 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700243 NewNode->OutEdges.push_back(this);
244 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700245 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700246 }
247 }
248 assert(Found);
Andrew Scull87f80c12015-07-20 10:19:16 -0700249 // Repoint all suitable branch instructions' target and return.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700250 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700251 for (Inst &I : Pred->getInsts())
252 if (!I.isDeleted() && I.repointEdges(this, NewNode))
253 Found = true;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700254 assert(Found);
255 return NewNode;
256}
257
258namespace {
259
260// Helper function used by advancedPhiLowering().
261bool sameVarOrReg(const Variable *Var, const Operand *Opnd) {
262 if (Var == Opnd)
263 return true;
264 if (const auto Var2 = llvm::dyn_cast<Variable>(Opnd)) {
265 if (Var->hasReg() && Var->getRegNum() == Var2->getRegNum())
266 return true;
267 }
268 return false;
269}
270
271} // end of anonymous namespace
272
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700273// This the "advanced" version of Phi lowering for a basic block, in contrast to
274// the simple version that lowers through assignments involving temporaries.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700275//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700276// All Phi instructions in a basic block are conceptually executed in parallel.
277// However, if we lower Phis early and commit to a sequential ordering, we may
278// end up creating unnecessary interferences which lead to worse register
279// allocation. Delaying Phi scheduling until after register allocation can help
280// unless there are no free registers for shuffling registers or stack slots and
281// spilling becomes necessary.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700282//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700283// The advanced Phi lowering starts by finding a topological sort of the Phi
284// instructions, where "A=B" comes before "B=C" due to the anti-dependence on B.
285// Preexisting register assignments are considered in the topological sort. If
286// a topological sort is not possible due to a cycle, the cycle is broken by
287// introducing a non-parallel temporary. For example, a cycle arising from a
288// permutation like "A=B;B=C;C=A" can become "T=A;A=B;B=C;C=T". All else being
289// equal, prefer to schedule assignments with register-allocated Src operands
290// earlier, in case that register becomes free afterwards, and prefer to
291// schedule assignments with register-allocated Dest variables later, to keep
292// that register free for longer.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700293//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700294// Once the ordering is determined, the Cfg edge is split and the assignment
295// list is lowered by the target lowering layer. Since the assignment lowering
296// may create new infinite-weight temporaries, a follow-on register allocation
297// pass will be needed. To prepare for this, liveness (including live range
298// calculation) of the split nodes needs to be calculated, and liveness of the
299// original node need to be updated to "undo" the effects of the phi
300// assignments.
301
302// The specific placement of the new node within the Cfg node list is deferred
303// until later, including after empty node contraction.
304//
305// After phi assignments are lowered across all blocks, another register
306// allocation pass is run, focusing only on pre-colored and infinite-weight
307// variables, similar to Om1 register allocation (except without the need to
308// specially compute these variables' live ranges, since they have already been
309// precisely calculated). The register allocator in this mode needs the ability
310// to forcibly spill and reload registers in case none are naturally available.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700311void CfgNode::advancedPhiLowering() {
312 if (getPhis().empty())
313 return;
314
315 // Count the number of non-deleted Phi instructions.
JF Bastienf2e93b62015-01-22 14:30:57 -0800316 struct PhiDesc {
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700317 InstPhi *Phi;
318 Variable *Dest;
319 Operand *Src;
320 bool Processed;
321 size_t NumPred; // number of entries whose Src is this Dest
322 int32_t Weight; // preference for topological order
JF Bastienf2e93b62015-01-22 14:30:57 -0800323 };
324 llvm::SmallVector<PhiDesc, 32> Desc(getPhis().size());
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700325
326 size_t NumPhis = 0;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800327 for (Inst &I : Phis) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700328 auto *Inst = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700329 if (!Inst->isDeleted()) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700330 Variable *Dest = Inst->getDest();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700331 Desc[NumPhis].Phi = Inst;
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700332 Desc[NumPhis].Dest = Dest;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700333 ++NumPhis;
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700334 // Undo the effect of the phi instruction on this node's live-in set by
335 // marking the phi dest variable as live on entry.
336 SizeT VarNum = Func->getLiveness()->getLiveIndex(Dest->getIndex());
337 assert(!Func->getLiveness()->getLiveIn(this)[VarNum]);
338 Func->getLiveness()->getLiveIn(this)[VarNum] = true;
339 Inst->setDeleted();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700340 }
341 }
342 if (NumPhis == 0)
343 return;
344
345 SizeT InEdgeIndex = 0;
346 for (CfgNode *Pred : InEdges) {
347 CfgNode *Split = splitIncomingEdge(Pred, InEdgeIndex++);
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700348 SizeT Remaining = NumPhis;
349
350 // First pass computes Src and initializes NumPred.
351 for (size_t I = 0; I < NumPhis; ++I) {
352 Variable *Dest = Desc[I].Dest;
353 Operand *Src = Desc[I].Phi->getOperandForTarget(Pred);
354 Desc[I].Src = Src;
355 Desc[I].Processed = false;
356 Desc[I].NumPred = 0;
357 // Cherry-pick any trivial assignments, so that they don't
358 // contribute to the running complexity of the topological sort.
359 if (sameVarOrReg(Dest, Src)) {
360 Desc[I].Processed = true;
361 --Remaining;
362 if (Dest != Src)
363 // If Dest and Src are syntactically the same, don't bother
364 // adding the assignment, because in all respects it would
365 // be redundant, and if Dest/Src are on the stack, the
366 // target lowering may naively decide to lower it using a
367 // temporary register.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700368 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700369 }
370 }
371 // Second pass computes NumPred by comparing every pair of Phi
372 // instructions.
373 for (size_t I = 0; I < NumPhis; ++I) {
374 if (Desc[I].Processed)
375 continue;
376 const Variable *Dest = Desc[I].Dest;
377 for (size_t J = 0; J < NumPhis; ++J) {
378 if (Desc[J].Processed)
379 continue;
380 if (I != J) {
381 // There shouldn't be two Phis with the same Dest variable
382 // or register.
383 assert(!sameVarOrReg(Dest, Desc[J].Dest));
384 }
385 const Operand *Src = Desc[J].Src;
386 if (sameVarOrReg(Dest, Src))
387 ++Desc[I].NumPred;
388 }
389 }
390
391 // Another pass to compute initial Weight values.
392
393 // Always pick NumPred=0 over NumPred>0.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700394 constexpr int32_t WeightNoPreds = 4;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700395 // Prefer Src as a register because the register might free up.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700396 constexpr int32_t WeightSrcIsReg = 2;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700397 // Prefer Dest not as a register because the register stays free
398 // longer.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700399 constexpr int32_t WeightDestNotReg = 1;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700400
401 for (size_t I = 0; I < NumPhis; ++I) {
402 if (Desc[I].Processed)
403 continue;
404 int32_t Weight = 0;
405 if (Desc[I].NumPred == 0)
406 Weight += WeightNoPreds;
407 if (auto Var = llvm::dyn_cast<Variable>(Desc[I].Src))
408 if (Var->hasReg())
409 Weight += WeightSrcIsReg;
410 if (!Desc[I].Dest->hasReg())
411 Weight += WeightDestNotReg;
412 Desc[I].Weight = Weight;
413 }
414
415 // Repeatedly choose and process the best candidate in the
416 // topological sort, until no candidates remain. This
417 // implementation is O(N^2) where N is the number of Phi
418 // instructions, but with a small constant factor compared to a
419 // likely implementation of O(N) topological sort.
420 for (; Remaining; --Remaining) {
421 size_t BestIndex = 0;
422 int32_t BestWeight = -1;
423 // Find the best candidate.
424 for (size_t I = 0; I < NumPhis; ++I) {
425 if (Desc[I].Processed)
426 continue;
427 int32_t Weight = 0;
428 Weight = Desc[I].Weight;
429 if (Weight > BestWeight) {
430 BestIndex = I;
431 BestWeight = Weight;
432 }
433 }
434 assert(BestWeight >= 0);
435 assert(Desc[BestIndex].NumPred <= 1);
436 Variable *Dest = Desc[BestIndex].Dest;
437 Operand *Src = Desc[BestIndex].Src;
438 assert(!sameVarOrReg(Dest, Src));
439 // Break a cycle by introducing a temporary.
440 if (Desc[BestIndex].NumPred) {
441 bool Found = false;
442 // If the target instruction "A=B" is part of a cycle, find
443 // the "X=A" assignment in the cycle because it will have to
444 // be rewritten as "X=tmp".
445 for (size_t J = 0; !Found && J < NumPhis; ++J) {
446 if (Desc[J].Processed)
447 continue;
448 Operand *OtherSrc = Desc[J].Src;
449 if (Desc[J].NumPred && sameVarOrReg(Dest, OtherSrc)) {
450 SizeT VarNum = Func->getNumVariables();
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800451 Variable *Tmp = Func->makeVariable(OtherSrc->getType());
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700452 if (BuildDefs::dump())
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800453 Tmp->setName(Func, "__split_" + std::to_string(VarNum));
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700454 Split->appendInst(InstAssign::create(Func, Tmp, OtherSrc));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700455 Desc[J].Src = Tmp;
456 Found = true;
457 }
458 }
459 assert(Found);
460 }
461 // Now that a cycle (if any) has been broken, create the actual
462 // assignment.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700463 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700464 // Update NumPred for all Phi assignments using this Phi's Src
465 // as their Dest variable. Also update Weight if NumPred
466 // dropped from 1 to 0.
467 if (auto Var = llvm::dyn_cast<Variable>(Src)) {
468 for (size_t I = 0; I < NumPhis; ++I) {
469 if (Desc[I].Processed)
470 continue;
471 if (sameVarOrReg(Var, Desc[I].Dest)) {
472 if (--Desc[I].NumPred == 0)
473 Desc[I].Weight += WeightNoPreds;
474 }
475 }
476 }
477 Desc[BestIndex].Processed = true;
478 }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700479 Split->appendInst(InstBr::create(Func, this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700480
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700481 Split->genCode();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700482 Func->getVMetadata()->addNode(Split);
483 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700484}
485
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700486// Does address mode optimization. Pass each instruction to the
487// TargetLowering object. If it returns a new instruction
488// (representing the optimized address mode), then insert the new
489// instruction and delete the old.
490void CfgNode::doAddressOpt() {
491 TargetLowering *Target = Func->getTarget();
492 LoweringContext &Context = Target->getContext();
493 Context.init(this);
494 while (!Context.atEnd()) {
495 Target->doAddressOpt();
496 }
497}
498
Qining Luaee5fa82015-08-20 14:59:03 -0700499void CfgNode::doNopInsertion(RandomNumberGenerator &RNG) {
Matt Walac3302742014-08-15 16:21:56 -0700500 TargetLowering *Target = Func->getTarget();
501 LoweringContext &Context = Target->getContext();
502 Context.init(this);
Qining Lu969f6a32015-07-31 09:58:34 -0700503 Context.setInsertPoint(Context.getCur());
504 // Do not insert nop in bundle locked instructions.
505 bool PauseNopInsertion = false;
Matt Walac3302742014-08-15 16:21:56 -0700506 while (!Context.atEnd()) {
Qining Lu969f6a32015-07-31 09:58:34 -0700507 if (llvm::isa<InstBundleLock>(Context.getCur())) {
508 PauseNopInsertion = true;
509 } else if (llvm::isa<InstBundleUnlock>(Context.getCur())) {
510 PauseNopInsertion = false;
511 }
512 if (!PauseNopInsertion)
Qining Luaee5fa82015-08-20 14:59:03 -0700513 Target->doNopInsertion(RNG);
Matt Walac3302742014-08-15 16:21:56 -0700514 // Ensure Cur=Next, so that the nops are inserted before the current
515 // instruction rather than after.
Matt Walac3302742014-08-15 16:21:56 -0700516 Context.advanceCur();
Qining Lu969f6a32015-07-31 09:58:34 -0700517 Context.advanceNext();
Matt Walac3302742014-08-15 16:21:56 -0700518 }
Matt Walac3302742014-08-15 16:21:56 -0700519}
520
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700521// Drives the target lowering. Passes the current instruction and the
522// next non-deleted instruction for target lowering.
523void CfgNode::genCode() {
524 TargetLowering *Target = Func->getTarget();
525 LoweringContext &Context = Target->getContext();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700526 // Lower the regular instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700527 Context.init(this);
Jim Stichnotha59ae6f2015-05-17 10:11:41 -0700528 Target->initNodeForLowering(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700529 while (!Context.atEnd()) {
530 InstList::iterator Orig = Context.getCur();
531 if (llvm::isa<InstRet>(*Orig))
532 setHasReturn();
533 Target->lower();
534 // Ensure target lowering actually moved the cursor.
535 assert(Context.getCur() != Orig);
536 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700537 // Do preliminary lowering of the Phi instructions.
538 Target->prelowerPhis();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700539}
540
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700541void CfgNode::livenessLightweight() {
542 SizeT NumVars = Func->getNumVariables();
Jim Stichnoth47752552014-10-13 17:15:08 -0700543 LivenessBV Live(NumVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700544 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800545 for (Inst &I : reverse_range(Insts)) {
546 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700547 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800548 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700549 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800550 for (Inst &I : Phis) {
551 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700552 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800553 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700554 }
555}
556
557// Performs liveness analysis on the block. Returns true if the
558// incoming liveness changed from before, false if it stayed the same.
559// (If it changes, the node's predecessors need to be processed
560// again.)
561bool CfgNode::liveness(Liveness *Liveness) {
562 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700563 LivenessBV Live(NumVars);
Jim Stichnothae953202014-12-20 06:17:49 -0800564 LiveBeginEndMap *LiveBegin = nullptr;
565 LiveBeginEndMap *LiveEnd = nullptr;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700566 // Mark the beginning and ending of each variable's live range
567 // with the sentinel instruction number 0.
Jim Stichnoth47752552014-10-13 17:15:08 -0700568 if (Liveness->getMode() == Liveness_Intervals) {
569 LiveBegin = Liveness->getLiveBegin(this);
570 LiveEnd = Liveness->getLiveEnd(this);
571 LiveBegin->clear();
572 LiveEnd->clear();
573 // Guess that the number of live ranges beginning is roughly the
574 // number of instructions, and same for live ranges ending.
575 LiveBegin->reserve(getInstCountEstimate());
576 LiveEnd->reserve(getInstCountEstimate());
577 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700578 // Initialize Live to be the union of all successors' LiveIn.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700579 for (CfgNode *Succ : OutEdges) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700580 Live |= Liveness->getLiveIn(Succ);
581 // Mark corresponding argument of phis in successor as live.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800582 for (Inst &I : Succ->Phis) {
Jim Stichnoth552490c2015-08-05 16:21:42 -0700583 if (I.isDeleted())
584 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800585 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800586 Phi->livenessPhiOperand(Live, this, Liveness);
587 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700588 }
589 Liveness->getLiveOut(this) = Live;
590
591 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800592 for (Inst &I : reverse_range(Insts)) {
593 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700594 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800595 I.liveness(I.getNumber(), Live, Liveness, LiveBegin, LiveEnd);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700596 }
597 // Process phis in forward order so that we can override the
598 // instruction number to be that of the earliest phi instruction in
599 // the block.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700600 SizeT NumNonDeadPhis = 0;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700601 InstNumberT FirstPhiNumber = Inst::NumberSentinel;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800602 for (Inst &I : Phis) {
603 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700604 continue;
605 if (FirstPhiNumber == Inst::NumberSentinel)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800606 FirstPhiNumber = I.getNumber();
607 if (I.liveness(FirstPhiNumber, Live, Liveness, LiveBegin, LiveEnd))
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700608 ++NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700609 }
610
611 // When using the sparse representation, after traversing the
612 // instructions in the block, the Live bitvector should only contain
613 // set bits for global variables upon block entry. We validate this
614 // by shrinking the Live vector and then testing it against the
615 // pre-shrunk version. (The shrinking is required, but the
616 // validation is not.)
Jim Stichnoth47752552014-10-13 17:15:08 -0700617 LivenessBV LiveOrig = Live;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700618 Live.resize(Liveness->getNumGlobalVars());
Jim Stichnothb3bfcbc2015-08-01 18:46:12 -0700619 if (Live != LiveOrig) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700620 if (BuildDefs::dump()) {
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700621 // This is a fatal liveness consistency error. Print some
622 // diagnostics and abort.
623 Ostream &Str = Func->getContext()->getStrDump();
624 Func->resetCurrentNode();
625 Str << "LiveOrig-Live =";
626 for (SizeT i = Live.size(); i < LiveOrig.size(); ++i) {
627 if (LiveOrig.test(i)) {
628 Str << " ";
629 Liveness->getVariable(i, this)->dump(Func);
630 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700631 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700632 Str << "\n";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700633 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700634 llvm::report_fatal_error("Fatal inconsistency in liveness analysis");
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700635 }
636
637 bool Changed = false;
Jim Stichnoth47752552014-10-13 17:15:08 -0700638 LivenessBV &LiveIn = Liveness->getLiveIn(this);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700639 // Add in current LiveIn
640 Live |= LiveIn;
641 // Check result, set LiveIn=Live
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700642 SizeT &PrevNumNonDeadPhis = Liveness->getNumNonDeadPhis(this);
643 bool LiveInChanged = (Live != LiveIn);
644 Changed = (NumNonDeadPhis != PrevNumNonDeadPhis || LiveInChanged);
645 if (LiveInChanged)
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700646 LiveIn = Live;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700647 PrevNumNonDeadPhis = NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700648 return Changed;
649}
650
Jim Stichnothe5b73e62014-12-15 09:58:51 -0800651// Once basic liveness is complete, compute actual live ranges. It is
652// assumed that within a single basic block, a live range begins at
653// most once and ends at most once. This is certainly true for pure
654// SSA form. It is also true once phis are lowered, since each
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700655// assignment to the phi-based temporary is in a different basic
656// block, and there is a single read that ends the live in the basic
657// block that contained the actual phi instruction.
Jim Stichnothe5b73e62014-12-15 09:58:51 -0800658void CfgNode::livenessAddIntervals(Liveness *Liveness, InstNumberT FirstInstNum,
659 InstNumberT LastInstNum) {
660 TimerMarker T1(TimerStack::TT_liveRange, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700661
662 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700663 LivenessBV &LiveIn = Liveness->getLiveIn(this);
664 LivenessBV &LiveOut = Liveness->getLiveOut(this);
665 LiveBeginEndMap &MapBegin = *Liveness->getLiveBegin(this);
666 LiveBeginEndMap &MapEnd = *Liveness->getLiveEnd(this);
667 std::sort(MapBegin.begin(), MapBegin.end());
668 std::sort(MapEnd.begin(), MapEnd.end());
669 // Verify there are no duplicates.
Jim Stichnothf9df4522015-08-06 17:50:14 -0700670 auto ComparePair =
671 [](const LiveBeginEndMapEntry &A, const LiveBeginEndMapEntry &B) {
672 return A.first == B.first;
673 };
Jim Stichnoth992f91d2015-08-10 11:18:38 -0700674 (void)ComparePair;
Jim Stichnothf9df4522015-08-06 17:50:14 -0700675 assert(std::adjacent_find(MapBegin.begin(), MapBegin.end(), ComparePair) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700676 MapBegin.end());
Jim Stichnothf9df4522015-08-06 17:50:14 -0700677 assert(std::adjacent_find(MapEnd.begin(), MapEnd.end(), ComparePair) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700678 MapEnd.end());
679
680 LivenessBV LiveInAndOut = LiveIn;
681 LiveInAndOut &= LiveOut;
682
683 // Iterate in parallel across the sorted MapBegin[] and MapEnd[].
684 auto IBB = MapBegin.begin(), IEB = MapEnd.begin();
685 auto IBE = MapBegin.end(), IEE = MapEnd.end();
686 while (IBB != IBE || IEB != IEE) {
687 SizeT i1 = IBB == IBE ? NumVars : IBB->first;
688 SizeT i2 = IEB == IEE ? NumVars : IEB->first;
689 SizeT i = std::min(i1, i2);
690 // i1 is the Variable number of the next MapBegin entry, and i2 is
691 // the Variable number of the next MapEnd entry. If i1==i2, then
692 // the Variable's live range begins and ends in this block. If
693 // i1<i2, then i1's live range begins at instruction IBB->second
694 // and extends through the end of the block. If i1>i2, then i2's
695 // live range begins at the first instruction of the block and
696 // ends at IEB->second. In any case, we choose the lesser of i1
697 // and i2 and proceed accordingly.
698 InstNumberT LB = i == i1 ? IBB->second : FirstInstNum;
699 InstNumberT LE = i == i2 ? IEB->second : LastInstNum + 1;
700
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700701 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnothf9df4522015-08-06 17:50:14 -0700702 if (LB > LE) {
Andrew Scull11c9a322015-08-28 14:24:14 -0700703 Var->addLiveRange(FirstInstNum, LE);
704 Var->addLiveRange(LB, LastInstNum + 1);
Jim Stichnothf9df4522015-08-06 17:50:14 -0700705 // Assert that Var is a global variable by checking that its
706 // liveness index is less than the number of globals. This
707 // ensures that the LiveInAndOut[] access is valid.
708 assert(i < Liveness->getNumGlobalVars());
709 LiveInAndOut[i] = false;
710 } else {
Andrew Scull11c9a322015-08-28 14:24:14 -0700711 Var->addLiveRange(LB, LE);
Jim Stichnoth47752552014-10-13 17:15:08 -0700712 }
713 if (i == i1)
714 ++IBB;
715 if (i == i2)
716 ++IEB;
717 }
718 // Process the variables that are live across the entire block.
719 for (int i = LiveInAndOut.find_first(); i != -1;
720 i = LiveInAndOut.find_next(i)) {
721 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth552490c2015-08-05 16:21:42 -0700722 if (Liveness->getRangeMask(Var->getIndex()))
Andrew Scull11c9a322015-08-28 14:24:14 -0700723 Var->addLiveRange(FirstInstNum, LastInstNum + 1);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700724 }
725}
726
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700727// If this node contains only deleted instructions, and ends in an
728// unconditional branch, contract the node by repointing all its
729// in-edges to its successor.
730void CfgNode::contractIfEmpty() {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800731 if (InEdges.empty())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700732 return;
Jim Stichnothae953202014-12-20 06:17:49 -0800733 Inst *Branch = nullptr;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800734 for (Inst &I : Insts) {
735 if (I.isDeleted())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700736 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800737 if (I.isUnconditionalBranch())
738 Branch = &I;
739 else if (!I.isRedundantAssign())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700740 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700741 }
742 Branch->setDeleted();
743 assert(OutEdges.size() == 1);
Andrew Scull713278a2015-07-22 17:17:02 -0700744 CfgNode *Successor = OutEdges.front();
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800745 // Repoint all this node's in-edges to this node's successor, unless
746 // this node's successor is actually itself (in which case the
747 // statement "OutEdges.front()->InEdges.push_back(Pred)" could
748 // invalidate the iterator over this->InEdges).
Andrew Scull713278a2015-07-22 17:17:02 -0700749 if (Successor != this) {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800750 for (CfgNode *Pred : InEdges) {
Andrew Scull713278a2015-07-22 17:17:02 -0700751 for (CfgNode *&I : Pred->OutEdges) {
752 if (I == this) {
753 I = Successor;
754 Successor->InEdges.push_back(Pred);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800755 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700756 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800757 for (Inst &I : Pred->getInsts()) {
758 if (!I.isDeleted())
Andrew Scull713278a2015-07-22 17:17:02 -0700759 I.repointEdges(this, Successor);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800760 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700761 }
Andrew Scull713278a2015-07-22 17:17:02 -0700762
763 // Remove the in-edge to the successor to allow node reordering to make
764 // better decisions. For example it's more helpful to place a node after
765 // a reachable predecessor than an unreachable one (like the one we just
766 // contracted).
767 Successor->InEdges.erase(
768 std::find(Successor->InEdges.begin(), Successor->InEdges.end(), this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700769 }
770 InEdges.clear();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700771}
772
Jim Stichnothff9c7062014-09-18 04:50:49 -0700773void CfgNode::doBranchOpt(const CfgNode *NextNode) {
774 TargetLowering *Target = Func->getTarget();
Andrew Scull713278a2015-07-22 17:17:02 -0700775 // Find the first opportunity for branch optimization (which will be the last
776 // instruction in the block) and stop. This is sufficient unless there is some
777 // target lowering where we have the possibility of multiple optimizations per
778 // block. Take care with switch lowering as there are multiple unconditional
779 // branches and only the last can be deleted.
780 for (Inst &I : reverse_range(Insts)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800781 if (!I.isDeleted()) {
782 Target->doBranchOpt(&I, NextNode);
Andrew Scull713278a2015-07-22 17:17:02 -0700783 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700784 }
785 }
Jim Stichnothff9c7062014-09-18 04:50:49 -0700786}
787
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700788// ======================== Dump routines ======================== //
789
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700790namespace {
791
792// Helper functions for emit().
793
794void emitRegisterUsage(Ostream &Str, const Cfg *Func, const CfgNode *Node,
795 bool IsLiveIn, std::vector<SizeT> &LiveRegCount) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700796 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800797 return;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700798 Liveness *Liveness = Func->getLiveness();
799 const LivenessBV *Live;
800 if (IsLiveIn) {
801 Live = &Liveness->getLiveIn(Node);
802 Str << "\t\t\t\t# LiveIn=";
803 } else {
804 Live = &Liveness->getLiveOut(Node);
805 Str << "\t\t\t\t# LiveOut=";
806 }
807 if (!Live->empty()) {
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700808 std::vector<Variable *> LiveRegs;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700809 for (SizeT i = 0; i < Live->size(); ++i) {
810 if ((*Live)[i]) {
811 Variable *Var = Liveness->getVariable(i, Node);
812 if (Var->hasReg()) {
813 if (IsLiveIn)
814 ++LiveRegCount[Var->getRegNum()];
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700815 LiveRegs.push_back(Var);
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700816 }
817 }
818 }
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700819 // Sort the variables by regnum so they are always printed in a
820 // familiar order.
821 std::sort(LiveRegs.begin(), LiveRegs.end(),
822 [](const Variable *V1, const Variable *V2) {
Jim Stichnoth8e6bf6e2015-06-03 15:58:12 -0700823 return V1->getRegNum() < V2->getRegNum();
824 });
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700825 bool First = true;
826 for (Variable *Var : LiveRegs) {
827 if (!First)
828 Str << ",";
829 First = false;
830 Var->emit(Func);
831 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700832 }
833 Str << "\n";
834}
835
836void emitLiveRangesEnded(Ostream &Str, const Cfg *Func, const Inst *Instr,
837 std::vector<SizeT> &LiveRegCount) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700838 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800839 return;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700840 bool First = true;
841 Variable *Dest = Instr->getDest();
Jim Stichnothb82baf22015-05-27 10:41:07 -0700842 // Normally we increment the live count for the dest register. But
843 // we shouldn't if the instruction's IsDestNonKillable flag is set,
844 // because this means that the target lowering created this
845 // instruction as a non-SSA assignment; i.e., a different, previous
846 // instruction started the dest variable's live range.
847 if (!Instr->isDestNonKillable() && Dest && Dest->hasReg())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700848 ++LiveRegCount[Dest->getRegNum()];
849 for (SizeT I = 0; I < Instr->getSrcSize(); ++I) {
850 Operand *Src = Instr->getSrc(I);
851 SizeT NumVars = Src->getNumVars();
852 for (SizeT J = 0; J < NumVars; ++J) {
853 const Variable *Var = Src->getVar(J);
Jim Stichnothb82baf22015-05-27 10:41:07 -0700854 bool ShouldReport = Instr->isLastUse(Var);
855 if (ShouldReport && Var->hasReg()) {
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700856 // Don't report end of live range until the live count reaches 0.
857 SizeT NewCount = --LiveRegCount[Var->getRegNum()];
858 if (NewCount)
Jim Stichnothb82baf22015-05-27 10:41:07 -0700859 ShouldReport = false;
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700860 }
Jim Stichnothb82baf22015-05-27 10:41:07 -0700861 if (ShouldReport) {
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700862 if (First)
863 Str << " \t# END=";
864 else
865 Str << ",";
866 Var->emit(Func);
867 First = false;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700868 }
869 }
870 }
871}
872
Jan Voung0faec4c2014-11-05 17:29:56 -0800873void updateStats(Cfg *Func, const Inst *I) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700874 if (!BuildDefs::dump())
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800875 return;
Jan Voung0faec4c2014-11-05 17:29:56 -0800876 // Update emitted instruction count, plus fill/spill count for
877 // Variable operands without a physical register.
878 if (uint32_t Count = I->getEmitInstCount()) {
879 Func->getContext()->statsUpdateEmitted(Count);
880 if (Variable *Dest = I->getDest()) {
881 if (!Dest->hasReg())
882 Func->getContext()->statsUpdateFills();
883 }
884 for (SizeT S = 0; S < I->getSrcSize(); ++S) {
885 if (Variable *Src = llvm::dyn_cast<Variable>(I->getSrc(S))) {
886 if (!Src->hasReg())
887 Func->getContext()->statsUpdateSpills();
888 }
889 }
890 }
891}
892
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700893} // end of anonymous namespace
894
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700895void CfgNode::emit(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700896 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800897 return;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700898 Func->setCurrentNode(this);
899 Ostream &Str = Func->getContext()->getStrEmit();
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700900 Liveness *Liveness = Func->getLiveness();
Karl Schimpfdf80eb82015-02-09 14:20:22 -0800901 bool DecorateAsm =
902 Liveness && Func->getContext()->getFlags().getDecorateAsm();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700903 Str << getAsmName() << ":\n";
Jim Stichnothb82baf22015-05-27 10:41:07 -0700904 // LiveRegCount keeps track of the number of currently live
905 // variables that each register is assigned to. Normally that would
906 // be only 0 or 1, but the register allocator's AllowOverlap
907 // inference allows it to be greater than 1 for short periods.
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700908 std::vector<SizeT> LiveRegCount(Func->getTarget()->getNumRegisters());
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700909 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700910 constexpr bool IsLiveIn = true;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700911 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
912 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700913
Jim Stichnoth29841e82014-12-23 12:26:24 -0800914 for (const Inst &I : Phis) {
915 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700916 continue;
917 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800918 I.emit(Func);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700919 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800920 for (const Inst &I : Insts) {
921 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700922 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -0700923 if (I.isRedundantAssign()) {
924 // Usually, redundant assignments end the live range of the src
925 // variable and begin the live range of the dest variable, with
926 // no net effect on the liveness of their register. However, if
927 // the register allocator infers the AllowOverlap condition,
928 // then this may be a redundant assignment that does not end the
929 // src variable's live range, in which case the active variable
930 // count for that register needs to be bumped. That normally
931 // would have happened as part of emitLiveRangesEnded(), but
932 // that isn't called for redundant assignments.
933 Variable *Dest = I.getDest();
934 if (DecorateAsm && Dest->hasReg() && !I.isLastUse(I.getSrc(0)))
935 ++LiveRegCount[Dest->getRegNum()];
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700936 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -0700937 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800938 I.emit(Func);
Jan Voung0faec4c2014-11-05 17:29:56 -0800939 if (DecorateAsm)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800940 emitLiveRangesEnded(Str, Func, &I, LiveRegCount);
Jan Voung0faec4c2014-11-05 17:29:56 -0800941 Str << "\n";
Jim Stichnoth29841e82014-12-23 12:26:24 -0800942 updateStats(Func, &I);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700943 }
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700944 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700945 constexpr bool IsLiveIn = false;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700946 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
947 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700948}
949
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800950// Helper class for emitIAS().
951namespace {
952class BundleEmitHelper {
953 BundleEmitHelper() = delete;
954 BundleEmitHelper(const BundleEmitHelper &) = delete;
955 BundleEmitHelper &operator=(const BundleEmitHelper &) = delete;
956
957public:
Jim Stichnoth9738a9e2015-02-23 16:39:06 -0800958 BundleEmitHelper(Assembler *Asm, TargetLowering *Target,
959 const InstList &Insts)
960 : Asm(Asm), Target(Target), End(Insts.end()), BundleLockStart(End),
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800961 BundleSize(1 << Asm->getBundleAlignLog2Bytes()),
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700962 BundleMaskLo(BundleSize - 1), BundleMaskHi(~BundleMaskLo) {}
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800963 // Check whether we're currently within a bundle_lock region.
964 bool isInBundleLockRegion() const { return BundleLockStart != End; }
965 // Check whether the current bundle_lock region has the align_to_end
966 // option.
967 bool isAlignToEnd() const {
968 assert(isInBundleLockRegion());
969 return llvm::cast<InstBundleLock>(getBundleLockStart())->getOption() ==
970 InstBundleLock::Opt_AlignToEnd;
971 }
972 // Check whether the entire bundle_lock region falls within the same
973 // bundle.
974 bool isSameBundle() const {
975 assert(isInBundleLockRegion());
976 return SizeSnapshotPre == SizeSnapshotPost ||
977 (SizeSnapshotPre & BundleMaskHi) ==
978 ((SizeSnapshotPost - 1) & BundleMaskHi);
979 }
980 // Get the bundle alignment of the first instruction of the
981 // bundle_lock region.
982 intptr_t getPreAlignment() const {
983 assert(isInBundleLockRegion());
984 return SizeSnapshotPre & BundleMaskLo;
985 }
986 // Get the bundle alignment of the first instruction past the
987 // bundle_lock region.
988 intptr_t getPostAlignment() const {
989 assert(isInBundleLockRegion());
990 return SizeSnapshotPost & BundleMaskLo;
991 }
992 // Get the iterator pointing to the bundle_lock instruction, e.g. to
993 // roll back the instruction iteration to that point.
994 InstList::const_iterator getBundleLockStart() const {
995 assert(isInBundleLockRegion());
996 return BundleLockStart;
997 }
998 // Set up bookkeeping when the bundle_lock instruction is first
999 // processed.
1000 void enterBundleLock(InstList::const_iterator I) {
1001 assert(!isInBundleLockRegion());
1002 BundleLockStart = I;
1003 SizeSnapshotPre = Asm->getBufferSize();
1004 Asm->setPreliminary(true);
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001005 Target->snapshotEmitState();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001006 assert(isInBundleLockRegion());
1007 }
1008 // Update bookkeeping when the bundle_unlock instruction is
1009 // processed.
1010 void enterBundleUnlock() {
1011 assert(isInBundleLockRegion());
1012 SizeSnapshotPost = Asm->getBufferSize();
1013 }
1014 // Update bookkeeping when we are completely finished with the
1015 // bundle_lock region.
1016 void leaveBundleLockRegion() { BundleLockStart = End; }
1017 // Check whether the instruction sequence fits within the current
1018 // bundle, and if not, add nop padding to the end of the current
1019 // bundle.
1020 void padToNextBundle() {
1021 assert(isInBundleLockRegion());
1022 if (!isSameBundle()) {
1023 intptr_t PadToNextBundle = BundleSize - getPreAlignment();
1024 Asm->padWithNop(PadToNextBundle);
1025 SizeSnapshotPre += PadToNextBundle;
1026 SizeSnapshotPost += PadToNextBundle;
1027 assert((Asm->getBufferSize() & BundleMaskLo) == 0);
1028 assert(Asm->getBufferSize() == SizeSnapshotPre);
1029 }
1030 }
1031 // If align_to_end is specified, add padding such that the
1032 // instruction sequences ends precisely at a bundle boundary.
1033 void padForAlignToEnd() {
1034 assert(isInBundleLockRegion());
1035 if (isAlignToEnd()) {
1036 if (intptr_t Offset = getPostAlignment()) {
1037 Asm->padWithNop(BundleSize - Offset);
1038 SizeSnapshotPre = Asm->getBufferSize();
1039 }
1040 }
1041 }
1042 // Update bookkeeping when rolling back for the second pass.
1043 void rollback() {
1044 assert(isInBundleLockRegion());
1045 Asm->setBufferSize(SizeSnapshotPre);
1046 Asm->setPreliminary(false);
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001047 Target->rollbackEmitState();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001048 }
1049
1050private:
1051 Assembler *const Asm;
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001052 TargetLowering *const Target;
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001053 // End is a sentinel value such that BundleLockStart==End implies
1054 // that we are not in a bundle_lock region.
1055 const InstList::const_iterator End;
1056 InstList::const_iterator BundleLockStart;
1057 const intptr_t BundleSize;
1058 // Masking with BundleMaskLo identifies an address's bundle offset.
1059 const intptr_t BundleMaskLo;
1060 // Masking with BundleMaskHi identifies an address's bundle.
1061 const intptr_t BundleMaskHi;
Jim Stichnotheafb56c2015-06-22 10:35:22 -07001062 intptr_t SizeSnapshotPre = 0;
1063 intptr_t SizeSnapshotPost = 0;
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001064};
1065
1066} // end of anonymous namespace
1067
Jan Voung0faec4c2014-11-05 17:29:56 -08001068void CfgNode::emitIAS(Cfg *Func) const {
1069 Func->setCurrentNode(this);
Jim Stichnothbbca7542015-02-11 16:08:31 -08001070 Assembler *Asm = Func->getAssembler<>();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001071 // TODO(stichnot): When sandboxing, defer binding the node label
1072 // until just before the first instruction is emitted, to reduce the
1073 // chance that a padding nop is a branch target.
John Portoaff4ccf2015-06-10 16:35:06 -07001074 Asm->bindCfgNodeLabel(getIndex());
Jim Stichnoth29841e82014-12-23 12:26:24 -08001075 for (const Inst &I : Phis) {
1076 if (I.isDeleted())
Jan Voung0faec4c2014-11-05 17:29:56 -08001077 continue;
1078 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -08001079 I.emitIAS(Func);
Jan Voung0faec4c2014-11-05 17:29:56 -08001080 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001081
1082 // Do the simple emission if not sandboxed.
1083 if (!Func->getContext()->getFlags().getUseSandboxing()) {
1084 for (const Inst &I : Insts) {
1085 if (!I.isDeleted() && !I.isRedundantAssign()) {
1086 I.emitIAS(Func);
1087 updateStats(Func, &I);
1088 }
1089 }
1090 return;
Jan Voung0faec4c2014-11-05 17:29:56 -08001091 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001092
1093 // The remainder of the function handles emission with sandboxing.
1094 // There are explicit bundle_lock regions delimited by bundle_lock
1095 // and bundle_unlock instructions. All other instructions are
1096 // treated as an implicit one-instruction bundle_lock region.
1097 // Emission is done twice for each bundle_lock region. The first
1098 // pass is a preliminary pass, after which we can figure out what
1099 // nop padding is needed, then roll back, and make the final pass.
1100 //
1101 // Ideally, the first pass would be speculative and the second pass
1102 // would only be done if nop padding were needed, but the structure
1103 // of the integrated assembler makes it hard to roll back the state
1104 // of label bindings, label links, and relocation fixups. Instead,
1105 // the first pass just disables all mutation of that state.
1106
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001107 BundleEmitHelper Helper(Asm, Func->getTarget(), Insts);
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001108 InstList::const_iterator End = Insts.end();
1109 // Retrying indicates that we had to roll back to the bundle_lock
1110 // instruction to apply padding before the bundle_lock sequence.
1111 bool Retrying = false;
1112 for (InstList::const_iterator I = Insts.begin(); I != End; ++I) {
1113 if (I->isDeleted() || I->isRedundantAssign())
1114 continue;
1115
1116 if (llvm::isa<InstBundleLock>(I)) {
1117 // Set up the initial bundle_lock state. This should not happen
1118 // while retrying, because the retry rolls back to the
1119 // instruction following the bundle_lock instruction.
1120 assert(!Retrying);
1121 Helper.enterBundleLock(I);
1122 continue;
1123 }
1124
1125 if (llvm::isa<InstBundleUnlock>(I)) {
1126 Helper.enterBundleUnlock();
1127 if (Retrying) {
1128 // Make sure all instructions are in the same bundle.
1129 assert(Helper.isSameBundle());
1130 // If align_to_end is specified, make sure the next
1131 // instruction begins the bundle.
1132 assert(!Helper.isAlignToEnd() || Helper.getPostAlignment() == 0);
1133 Helper.leaveBundleLockRegion();
1134 Retrying = false;
1135 } else {
1136 // This is the first pass, so roll back for the retry pass.
1137 Helper.rollback();
1138 // Pad to the next bundle if the instruction sequence crossed
1139 // a bundle boundary.
1140 Helper.padToNextBundle();
1141 // Insert additional padding to make AlignToEnd work.
1142 Helper.padForAlignToEnd();
1143 // Prepare for the retry pass after padding is done.
1144 Retrying = true;
1145 I = Helper.getBundleLockStart();
1146 }
1147 continue;
1148 }
1149
1150 // I points to a non bundle_lock/bundle_unlock instruction.
1151 if (Helper.isInBundleLockRegion()) {
1152 I->emitIAS(Func);
1153 // Only update stats during the final pass.
1154 if (Retrying)
1155 updateStats(Func, I);
1156 } else {
1157 // Treat it as though there were an implicit bundle_lock and
1158 // bundle_unlock wrapping the instruction.
1159 Helper.enterBundleLock(I);
1160 I->emitIAS(Func);
1161 Helper.enterBundleUnlock();
1162 Helper.rollback();
1163 Helper.padToNextBundle();
1164 I->emitIAS(Func);
1165 updateStats(Func, I);
1166 Helper.leaveBundleLockRegion();
1167 }
1168 }
1169
1170 // Don't allow bundle locking across basic blocks, to keep the
1171 // backtracking mechanism simple.
1172 assert(!Helper.isInBundleLockRegion());
1173 assert(!Retrying);
Jan Voung0faec4c2014-11-05 17:29:56 -08001174}
1175
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001176void CfgNode::dump(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001177 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -08001178 return;
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001179 Func->setCurrentNode(this);
1180 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001181 Liveness *Liveness = Func->getLiveness();
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001182 if (Func->isVerbose(IceV_Instructions)) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001183 Str << getName() << ":\n";
1184 }
1185 // Dump list of predecessor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001186 if (Func->isVerbose(IceV_Preds) && !InEdges.empty()) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001187 Str << " // preds = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001188 bool First = true;
1189 for (CfgNode *I : InEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001190 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001191 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001192 First = false;
1193 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001194 }
1195 Str << "\n";
1196 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001197 // Dump the live-in variables.
Jim Stichnoth47752552014-10-13 17:15:08 -07001198 LivenessBV LiveIn;
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001199 if (Liveness)
1200 LiveIn = Liveness->getLiveIn(this);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001201 if (Func->isVerbose(IceV_Liveness) && !LiveIn.empty()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001202 Str << " // LiveIn:";
1203 for (SizeT i = 0; i < LiveIn.size(); ++i) {
1204 if (LiveIn[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001205 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth9a04c072014-12-11 15:51:42 -08001206 Str << " %" << Var->getName(Func);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001207 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
Jim Stichnothdd842db2015-01-27 12:53:53 -08001208 Str << ":"
1209 << Func->getTarget()->getRegName(Var->getRegNum(),
1210 Var->getType());
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001211 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001212 }
1213 }
1214 Str << "\n";
1215 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001216 // Dump each instruction.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001217 if (Func->isVerbose(IceV_Instructions)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -08001218 for (const Inst &I : Phis)
1219 I.dumpDecorated(Func);
1220 for (const Inst &I : Insts)
1221 I.dumpDecorated(Func);
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001222 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001223 // Dump the live-out variables.
Jim Stichnoth47752552014-10-13 17:15:08 -07001224 LivenessBV LiveOut;
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001225 if (Liveness)
1226 LiveOut = Liveness->getLiveOut(this);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001227 if (Func->isVerbose(IceV_Liveness) && !LiveOut.empty()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001228 Str << " // LiveOut:";
1229 for (SizeT i = 0; i < LiveOut.size(); ++i) {
1230 if (LiveOut[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001231 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth9a04c072014-12-11 15:51:42 -08001232 Str << " %" << Var->getName(Func);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001233 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
Jim Stichnothdd842db2015-01-27 12:53:53 -08001234 Str << ":"
1235 << Func->getTarget()->getRegName(Var->getRegNum(),
1236 Var->getType());
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001237 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001238 }
1239 }
1240 Str << "\n";
1241 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001242 // Dump list of successor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001243 if (Func->isVerbose(IceV_Succs)) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001244 Str << " // succs = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001245 bool First = true;
1246 for (CfgNode *I : OutEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001247 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001248 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001249 First = false;
1250 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001251 }
1252 Str << "\n";
1253 }
1254}
1255
John Portof8b4cc82015-06-09 18:06:19 -07001256void CfgNode::profileExecutionCount(VariableDeclaration *Var) {
1257 constexpr char RMW_I64[] = "llvm.nacl.atomic.rmw.i64";
1258
1259 GlobalContext *Context = Func->getContext();
1260
1261 bool BadIntrinsic = false;
1262 const Intrinsics::FullIntrinsicInfo *Info =
1263 Context->getIntrinsicsInfo().find(RMW_I64, BadIntrinsic);
1264 assert(!BadIntrinsic);
1265 assert(Info != nullptr);
1266
1267 Operand *RMWI64Name = Context->getConstantExternSym(RMW_I64);
John Porto8b1a7052015-06-17 13:20:08 -07001268 constexpr RelocOffsetT Offset = 0;
1269 constexpr bool SuppressMangling = true;
1270 Constant *Counter =
1271 Context->getConstantSym(Offset, Var->getName(), SuppressMangling);
John Portof8b4cc82015-06-09 18:06:19 -07001272 Constant *AtomicRMWOp = Context->getConstantInt32(Intrinsics::AtomicAdd);
1273 Constant *One = Context->getConstantInt64(1);
1274 Constant *OrderAcquireRelease =
1275 Context->getConstantInt32(Intrinsics::MemoryOrderAcquireRelease);
1276
1277 InstIntrinsicCall *Inst = InstIntrinsicCall::create(
1278 Func, 5, Func->makeVariable(IceType_i64), RMWI64Name, Info->Info);
1279 Inst->addArg(AtomicRMWOp);
1280 Inst->addArg(Counter);
1281 Inst->addArg(One);
1282 Inst->addArg(OrderAcquireRelease);
1283 Insts.push_front(Inst);
1284}
1285
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001286} // end of namespace Ice