blob: 33863da468df6af7e4ec2d85889e8ccb72923098 [file] [log] [blame]
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001//===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Vlad Tsyrklevich3b59a8a2018-04-26 17:34:51 +000010// This library implements `print` family of functions in classes like
11// Module, Function, Value, etc. In-memory representation of those classes is
12// converted to IR strings.
Chris Lattner2f7c9632001-06-06 20:29:01 +000013//
Chris Lattner189088e2002-04-12 18:21:53 +000014// Note that these routines must be extremely tolerant of various errors in the
Chris Lattnerf70da102003-05-08 02:44:12 +000015// LLVM code, because it can be used for debugging transformations.
Chris Lattner189088e2002-04-12 18:21:53 +000016//
Chris Lattner2f7c9632001-06-06 20:29:01 +000017//===----------------------------------------------------------------------===//
18
Eugene Zelenkode6cce22017-06-19 22:05:08 +000019#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/DenseMap.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000023#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/ADT/STLExtras.h"
Benjamin Kramerba05a782015-03-17 19:53:41 +000026#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/SmallString.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000028#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/ADT/StringExtras.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000030#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/iterator_range.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Nico Weber432a3882018-04-30 14:59:11 +000033#include "llvm/Config/llvm-config.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000034#include "llvm/IR/Argument.h"
Chandler Carruth9aca9182014-01-07 12:34:26 +000035#include "llvm/IR/AssemblyAnnotationWriter.h"
Reid Klecknereb9dd5b2017-04-10 23:31:05 +000036#include "llvm/IR/Attributes.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000037#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000038#include "llvm/IR/CFG.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000039#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/CallingConv.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000041#include "llvm/IR/Comdat.h"
42#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Constants.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000044#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000046#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalAlias.h"
48#include "llvm/IR/GlobalIFunc.h"
49#include "llvm/IR/GlobalIndirectSymbol.h"
50#include "llvm/IR/GlobalObject.h"
51#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/GlobalVariable.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000053#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/InlineAsm.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000055#include "llvm/IR/InstrTypes.h"
56#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/LLVMContext.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000059#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +000061#include "llvm/IR/ModuleSlotTracker.h"
Teresa Johnson08d5b4e2018-05-26 02:34:13 +000062#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/Operator.h"
Igor Laevsky2aa8caf2015-05-05 13:20:42 +000064#include "llvm/IR/Statepoint.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000065#include "llvm/IR/Type.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000066#include "llvm/IR/TypeFinder.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000067#include "llvm/IR/Use.h"
Benjamin Kramerba05a782015-03-17 19:53:41 +000068#include "llvm/IR/UseListOrder.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000069#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
71#include "llvm/Support/AtomicOrdering.h"
72#include "llvm/Support/Casting.h"
73#include "llvm/Support/Compiler.h"
David Greenec7f9b122010-01-05 01:29:26 +000074#include "llvm/Support/Debug.h"
Torok Edwin6dd27302009-07-08 18:01:40 +000075#include "llvm/Support/ErrorHandling.h"
Justin Bogner93289572015-12-04 02:14:34 +000076#include "llvm/Support/Format.h"
Dan Gohmane2745262009-08-12 17:23:50 +000077#include "llvm/Support/FormattedStream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000078#include "llvm/Support/raw_ostream.h"
Chris Lattnerfee714f2001-09-07 16:36:04 +000079#include <algorithm>
Eugene Zelenkode6cce22017-06-19 22:05:08 +000080#include <cassert>
Reid Spencerbdf03b42007-05-22 19:27:35 +000081#include <cctype>
Eugene Zelenkode6cce22017-06-19 22:05:08 +000082#include <cstddef>
83#include <cstdint>
84#include <iterator>
85#include <memory>
86#include <string>
87#include <tuple>
88#include <utility>
89#include <vector>
90
Chris Lattner189d19f2003-11-21 20:23:48 +000091using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000092
Reid Spencer294715b2005-05-15 16:13:11 +000093// Make virtual table appear in this compilation unit.
Eugene Zelenkode6cce22017-06-19 22:05:08 +000094AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
Reid Spencer294715b2005-05-15 16:13:11 +000095
Chris Lattner3eee99c2008-08-19 04:36:02 +000096//===----------------------------------------------------------------------===//
97// Helper Functions
98//===----------------------------------------------------------------------===//
99
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000100namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000101
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000102struct OrderMap {
103 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
104
105 unsigned size() const { return IDs.size(); }
106 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000107
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000108 std::pair<unsigned, bool> lookup(const Value *V) const {
109 return IDs.lookup(V);
110 }
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000111
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000112 void index(const Value *V) {
113 // Explicitly sequence get-size and insert-value operations to avoid UB.
114 unsigned ID = IDs.size() + 1;
115 IDs[V].first = ID;
116 }
117};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000118
119} // end anonymous namespace
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000120
121static void orderValue(const Value *V, OrderMap &OM) {
122 if (OM.lookup(V).first)
123 return;
124
125 if (const Constant *C = dyn_cast<Constant>(V))
126 if (C->getNumOperands() && !isa<GlobalValue>(C))
127 for (const Value *Op : C->operands())
128 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
129 orderValue(Op, OM);
130
131 // Note: we cannot cache this lookup above, since inserting into the map
132 // changes the map's size, and thus affects the other IDs.
133 OM.index(V);
134}
135
136static OrderMap orderModule(const Module *M) {
137 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
138 // and ValueEnumerator::incorporateFunction().
139 OrderMap OM;
140
141 for (const GlobalVariable &G : M->globals()) {
142 if (G.hasInitializer())
143 if (!isa<GlobalValue>(G.getInitializer()))
144 orderValue(G.getInitializer(), OM);
145 orderValue(&G, OM);
146 }
147 for (const GlobalAlias &A : M->aliases()) {
148 if (!isa<GlobalValue>(A.getAliasee()))
149 orderValue(A.getAliasee(), OM);
150 orderValue(&A, OM);
151 }
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000152 for (const GlobalIFunc &I : M->ifuncs()) {
153 if (!isa<GlobalValue>(I.getResolver()))
154 orderValue(I.getResolver(), OM);
155 orderValue(&I, OM);
156 }
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000157 for (const Function &F : *M) {
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000158 for (const Use &U : F.operands())
159 if (!isa<GlobalValue>(U.get()))
160 orderValue(U.get(), OM);
David Majnemer7fddecc2015-06-17 20:52:32 +0000161
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000162 orderValue(&F, OM);
163
164 if (F.isDeclaration())
165 continue;
166
167 for (const Argument &A : F.args())
168 orderValue(&A, OM);
169 for (const BasicBlock &BB : F) {
170 orderValue(&BB, OM);
171 for (const Instruction &I : BB) {
172 for (const Value *Op : I.operands())
173 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
174 isa<InlineAsm>(*Op))
175 orderValue(Op, OM);
176 orderValue(&I, OM);
177 }
178 }
179 }
180 return OM;
181}
182
183static void predictValueUseListOrderImpl(const Value *V, const Function *F,
184 unsigned ID, const OrderMap &OM,
185 UseListOrderStack &Stack) {
186 // Predict use-list order for this one.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000187 using Entry = std::pair<const Use *, unsigned>;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000188 SmallVector<Entry, 64> List;
189 for (const Use &U : V->uses())
190 // Check if this user will be serialized.
191 if (OM.lookup(U.getUser()).first)
192 List.push_back(std::make_pair(&U, List.size()));
193
194 if (List.size() < 2)
195 // We may have lost some users.
196 return;
197
198 bool GetsReversed =
199 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
200 if (auto *BA = dyn_cast<BlockAddress>(V))
201 ID = OM.lookup(BA->getBasicBlock()).first;
Fangrui Song0cac7262018-09-27 02:13:45 +0000202 llvm::sort(List, [&](const Entry &L, const Entry &R) {
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000203 const Use *LU = L.first;
204 const Use *RU = R.first;
205 if (LU == RU)
206 return false;
207
208 auto LID = OM.lookup(LU->getUser()).first;
209 auto RID = OM.lookup(RU->getUser()).first;
210
211 // If ID is 4, then expect: 7 6 5 1 2 3.
212 if (LID < RID) {
213 if (GetsReversed)
214 if (RID <= ID)
215 return true;
216 return false;
217 }
218 if (RID < LID) {
219 if (GetsReversed)
220 if (LID <= ID)
221 return false;
222 return true;
223 }
224
225 // LID and RID are equal, so we have different operands of the same user.
226 // Assume operands are added in order for all instructions.
227 if (GetsReversed)
228 if (LID <= ID)
229 return LU->getOperandNo() < RU->getOperandNo();
230 return LU->getOperandNo() > RU->getOperandNo();
231 });
232
233 if (std::is_sorted(
234 List.begin(), List.end(),
235 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
236 // Order is already correct.
237 return;
238
239 // Store the shuffle.
240 Stack.emplace_back(V, F, List.size());
241 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
242 for (size_t I = 0, E = List.size(); I != E; ++I)
243 Stack.back().Shuffle[I] = List[I].second;
244}
245
246static void predictValueUseListOrder(const Value *V, const Function *F,
247 OrderMap &OM, UseListOrderStack &Stack) {
248 auto &IDPair = OM[V];
249 assert(IDPair.first && "Unmapped value");
250 if (IDPair.second)
251 // Already predicted.
252 return;
253
254 // Do the actual prediction.
255 IDPair.second = true;
256 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
257 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
258
259 // Recursive descent into constants.
260 if (const Constant *C = dyn_cast<Constant>(V))
261 if (C->getNumOperands()) // Visit GlobalValues.
262 for (const Value *Op : C->operands())
263 if (isa<Constant>(Op)) // Visit GlobalValues.
264 predictValueUseListOrder(Op, F, OM, Stack);
265}
266
267static UseListOrderStack predictUseListOrder(const Module *M) {
268 OrderMap OM = orderModule(M);
269
270 // Use-list orders need to be serialized after all the users have been added
271 // to a value, or else the shuffles will be incomplete. Store them per
272 // function in a stack.
273 //
274 // Aside from function order, the order of values doesn't matter much here.
275 UseListOrderStack Stack;
276
277 // We want to visit the functions backward now so we can list function-local
278 // constants in the last Function they're used in. Module-level constants
279 // have already been visited above.
Pete Cooper7679afd2015-07-24 21:13:43 +0000280 for (const Function &F : make_range(M->rbegin(), M->rend())) {
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000281 if (F.isDeclaration())
282 continue;
283 for (const BasicBlock &BB : F)
284 predictValueUseListOrder(&BB, &F, OM, Stack);
285 for (const Argument &A : F.args())
286 predictValueUseListOrder(&A, &F, OM, Stack);
287 for (const BasicBlock &BB : F)
288 for (const Instruction &I : BB)
289 for (const Value *Op : I.operands())
290 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
291 predictValueUseListOrder(Op, &F, OM, Stack);
292 for (const BasicBlock &BB : F)
293 for (const Instruction &I : BB)
294 predictValueUseListOrder(&I, &F, OM, Stack);
295 }
296
297 // Visit globals last.
298 for (const GlobalVariable &G : M->globals())
299 predictValueUseListOrder(&G, nullptr, OM, Stack);
300 for (const Function &F : *M)
301 predictValueUseListOrder(&F, nullptr, OM, Stack);
302 for (const GlobalAlias &A : M->aliases())
303 predictValueUseListOrder(&A, nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000304 for (const GlobalIFunc &I : M->ifuncs())
305 predictValueUseListOrder(&I, nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000306 for (const GlobalVariable &G : M->globals())
307 if (G.hasInitializer())
308 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
309 for (const GlobalAlias &A : M->aliases())
310 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000311 for (const GlobalIFunc &I : M->ifuncs())
312 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000313 for (const Function &F : *M)
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000314 for (const Use &U : F.operands())
315 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000316
317 return Stack;
318}
319
Chris Lattner3eee99c2008-08-19 04:36:02 +0000320static const Module *getModuleFromVal(const Value *V) {
321 if (const Argument *MA = dyn_cast<Argument>(V))
Craig Topperc6207612014-04-09 06:08:46 +0000322 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000323
Chris Lattner3eee99c2008-08-19 04:36:02 +0000324 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
Craig Topperc6207612014-04-09 06:08:46 +0000325 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000326
Chris Lattner3eee99c2008-08-19 04:36:02 +0000327 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Craig Topperc6207612014-04-09 06:08:46 +0000328 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
329 return M ? M->getParent() : nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000330 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000331
Chris Lattner3eee99c2008-08-19 04:36:02 +0000332 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
333 return GV->getParent();
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000334
335 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
336 for (const User *U : MAV->users())
337 if (isa<Instruction>(U))
338 if (const Module *M = getModuleFromVal(U))
339 return M;
340 return nullptr;
341 }
342
Craig Topperc6207612014-04-09 06:08:46 +0000343 return nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000344}
345
Bill Wendling90bc19c2013-02-20 07:21:42 +0000346static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
Micah Villmow857186d2012-09-13 15:11:12 +0000347 switch (cc) {
Bill Wendling90bc19c2013-02-20 07:21:42 +0000348 default: Out << "cc" << cc; break;
349 case CallingConv::Fast: Out << "fastcc"; break;
350 case CallingConv::Cold: Out << "coldcc"; break;
Andrew Trick5ae6ed82013-11-11 22:40:22 +0000351 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
352 case CallingConv::AnyReg: Out << "anyregcc"; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +0000353 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
354 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +0000355 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +0000356 case CallingConv::GHC: Out << "ghccc"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000357 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
358 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
359 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +0000360 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +0000361 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000362 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
363 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
364 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
365 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
Sander de Smalen4dbc5122018-09-12 08:54:06 +0000366 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000367 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +0000368 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
369 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000370 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
371 case CallingConv::PTX_Device: Out << "ptx_device"; break;
Charles Davise8f297c2013-07-12 06:02:35 +0000372 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +0000373 case CallingConv::Win64: Out << "win64cc"; break;
Michael Kupersteine31b4862013-12-15 10:01:20 +0000374 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
375 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
Manman Renf8bdd882016-04-05 22:41:47 +0000376 case CallingConv::Swift: Out << "swiftcc"; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +0000377 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +0000378 case CallingConv::HHVM: Out << "hhvmcc"; break;
379 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +0000380 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +0000381 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
Marek Olsaka302a7362017-05-02 15:41:10 +0000382 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +0000383 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +0000384 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
385 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
386 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +0000387 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
Micah Villmow857186d2012-09-13 15:11:12 +0000388 }
389}
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000390
Chris Lattner3eee99c2008-08-19 04:36:02 +0000391enum PrefixType {
392 GlobalPrefix,
David Majnemerdad0a642014-06-27 18:19:56 +0000393 ComdatPrefix,
Chris Lattner3eee99c2008-08-19 04:36:02 +0000394 LabelPrefix,
Daniel Dunbar389529a2008-10-14 23:28:09 +0000395 LocalPrefix,
396 NoPrefix
Chris Lattner3eee99c2008-08-19 04:36:02 +0000397};
398
Alex Lorenz2b7f2652015-07-21 16:50:35 +0000399void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
Jay Foadf7adb322011-04-24 14:30:00 +0000400 assert(!Name.empty() && "Cannot get empty name!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000401
Chris Lattner3eee99c2008-08-19 04:36:02 +0000402 // Scan the name to see if it needs quotes first.
Guy Benyei83c74e92013-02-12 21:21:59 +0000403 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
Chris Lattner3eee99c2008-08-19 04:36:02 +0000404 if (!NeedsQuotes) {
Daniel Dunbare03eecb2009-07-25 23:55:21 +0000405 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
Aaron Ballmaned9b0a92012-07-16 16:18:18 +0000406 // By making this unsigned, the value passed in to isalnum will always be
407 // in the range 0-255. This is important when building with MSVC because
408 // its implementation will assert. This situation can arise when dealing
409 // with UTF-8 multibyte characters.
410 unsigned char C = Name[i];
Guy Benyei83c74e92013-02-12 21:21:59 +0000411 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
412 C != '_') {
Chris Lattner3eee99c2008-08-19 04:36:02 +0000413 NeedsQuotes = true;
414 break;
415 }
416 }
417 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000418
Chris Lattner3eee99c2008-08-19 04:36:02 +0000419 // If we didn't need any quotes, just write out the name in one blast.
420 if (!NeedsQuotes) {
Daniel Dunbare03eecb2009-07-25 23:55:21 +0000421 OS << Name;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000422 return;
423 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000424
Chris Lattner3eee99c2008-08-19 04:36:02 +0000425 // Okay, we need quotes. Output the quotes and escape any scary characters as
426 // needed.
427 OS << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +0000428 printEscapedString(Name, OS);
Chris Lattner3eee99c2008-08-19 04:36:02 +0000429 OS << '"';
430}
431
Alex Lorenz2b7f2652015-07-21 16:50:35 +0000432/// Turn the specified name into an 'LLVM name', which is either prefixed with %
433/// (if the string only contains simple characters) or is surrounded with ""'s
434/// (if it has special chars in it). Print it out.
435static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
436 switch (Prefix) {
437 case NoPrefix:
438 break;
439 case GlobalPrefix:
440 OS << '@';
441 break;
442 case ComdatPrefix:
443 OS << '$';
444 break;
445 case LabelPrefix:
446 break;
447 case LocalPrefix:
448 OS << '%';
449 break;
450 }
451 printLLVMNameWithoutPrefix(OS, Name);
452}
453
454/// Turn the specified name into an 'LLVM name', which is either prefixed with %
455/// (if the string only contains simple characters) or is surrounded with ""'s
456/// (if it has special chars in it). Print it out.
Dan Gohman12dad632009-08-12 20:56:03 +0000457static void PrintLLVMName(raw_ostream &OS, const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000458 PrintLLVMName(OS, V->getName(),
Chris Lattner3eee99c2008-08-19 04:36:02 +0000459 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
460}
461
Benjamin Kramerba05a782015-03-17 19:53:41 +0000462namespace {
Benjamin Kramerba05a782015-03-17 19:53:41 +0000463
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000464class TypePrinting {
465public:
Roman Tereshind96de6f2018-03-22 21:29:07 +0000466 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
Benjamin Kramerba05a782015-03-17 19:53:41 +0000467
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000468 TypePrinting(const TypePrinting &) = delete;
469 TypePrinting &operator=(const TypePrinting &) = delete;
Benjamin Kramerba05a782015-03-17 19:53:41 +0000470
Roman Tereshind96de6f2018-03-22 21:29:07 +0000471 /// The named types that are used by the current module.
472 TypeFinder &getNamedTypes();
473
474 /// The numbered types, number to type mapping.
475 std::vector<StructType *> &getNumberedTypes();
476
477 bool empty();
Benjamin Kramerba05a782015-03-17 19:53:41 +0000478
479 void print(Type *Ty, raw_ostream &OS);
480
481 void printStructBody(StructType *Ty, raw_ostream &OS);
Roman Tereshind96de6f2018-03-22 21:29:07 +0000482
483private:
484 void incorporateTypes();
485
486 /// A module to process lazily when needed. Set to nullptr as soon as used.
487 const Module *DeferredM;
488
489 TypeFinder NamedTypes;
490
491 // The numbered types, along with their value.
492 DenseMap<StructType *, unsigned> Type2Number;
493
494 std::vector<StructType *> NumberedTypes;
Benjamin Kramerba05a782015-03-17 19:53:41 +0000495};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000496
497} // end anonymous namespace
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000498
Roman Tereshind96de6f2018-03-22 21:29:07 +0000499TypeFinder &TypePrinting::getNamedTypes() {
500 incorporateTypes();
501 return NamedTypes;
502}
503
504std::vector<StructType *> &TypePrinting::getNumberedTypes() {
505 incorporateTypes();
506
507 // We know all the numbers that each type is used and we know that it is a
508 // dense assignment. Convert the map to an index table, if it's not done
509 // already (judging from the sizes):
510 if (NumberedTypes.size() == Type2Number.size())
511 return NumberedTypes;
512
513 NumberedTypes.resize(Type2Number.size());
514 for (const auto &P : Type2Number) {
515 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
516 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
517 NumberedTypes[P.second] = P.first;
518 }
519 return NumberedTypes;
520}
521
522bool TypePrinting::empty() {
523 incorporateTypes();
524 return NamedTypes.empty() && Type2Number.empty();
525}
526
527void TypePrinting::incorporateTypes() {
528 if (!DeferredM)
529 return;
530
531 NamedTypes.run(*DeferredM, false);
532 DeferredM = nullptr;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000533
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000534 // The list of struct types we got back includes all the struct types, split
535 // the unnamed ones out to a numbering and remove the anonymous structs.
536 unsigned NextNumber = 0;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000537
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000538 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
539 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
540 StructType *STy = *I;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000541
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000542 // Ignore anonymous types.
Chris Lattner01beceb2011-08-12 18:07:07 +0000543 if (STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000544 continue;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000545
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000546 if (STy->getName().empty())
Roman Tereshind96de6f2018-03-22 21:29:07 +0000547 Type2Number[STy] = NextNumber++;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000548 else
549 *NextToUse++ = STy;
550 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000551
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000552 NamedTypes.erase(NextToUse, NamedTypes.end());
553}
554
Roman Tereshind96de6f2018-03-22 21:29:07 +0000555/// Write the specified type to the specified raw_ostream, making use of type
556/// names or up references to shorten the type name where possible.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000557void TypePrinting::print(Type *Ty, raw_ostream &OS) {
Chris Lattner0f578952009-02-28 20:25:14 +0000558 switch (Ty->getTypeID()) {
Rafael Espindolaba7df702013-12-07 02:27:52 +0000559 case Type::VoidTyID: OS << "void"; return;
560 case Type::HalfTyID: OS << "half"; return;
561 case Type::FloatTyID: OS << "float"; return;
562 case Type::DoubleTyID: OS << "double"; return;
563 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
564 case Type::FP128TyID: OS << "fp128"; return;
565 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
566 case Type::LabelTyID: OS << "label"; return;
567 case Type::MetadataTyID: OS << "metadata"; return;
568 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
David Majnemerb611e3f2015-08-14 05:09:07 +0000569 case Type::TokenTyID: OS << "token"; return;
Chris Lattner68318b12009-02-28 21:18:43 +0000570 case Type::IntegerTyID:
Chris Lattner06a23212009-02-28 21:27:31 +0000571 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000572 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573
Chris Lattner07d88292009-02-28 20:35:42 +0000574 case Type::FunctionTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 FunctionType *FTy = cast<FunctionType>(Ty);
576 print(FTy->getReturnType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000577 OS << " (";
Chris Lattner07d88292009-02-28 20:35:42 +0000578 for (FunctionType::param_iterator I = FTy->param_begin(),
579 E = FTy->param_end(); I != E; ++I) {
580 if (I != FTy->param_begin())
Chris Lattner06a23212009-02-28 21:27:31 +0000581 OS << ", ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000582 print(*I, OS);
Chris Lattner0f578952009-02-28 20:25:14 +0000583 }
Chris Lattner07d88292009-02-28 20:35:42 +0000584 if (FTy->isVarArg()) {
Chris Lattner06a23212009-02-28 21:27:31 +0000585 if (FTy->getNumParams()) OS << ", ";
586 OS << "...";
Chris Lattner0f578952009-02-28 20:25:14 +0000587 }
Chris Lattner06a23212009-02-28 21:27:31 +0000588 OS << ')';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000589 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000590 }
591 case Type::StructTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000592 StructType *STy = cast<StructType>(Ty);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000593
Chris Lattner01beceb2011-08-12 18:07:07 +0000594 if (STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000595 return printStructBody(STy, OS);
596
597 if (!STy->getName().empty())
598 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000599
Roman Tereshind96de6f2018-03-22 21:29:07 +0000600 incorporateTypes();
601 const auto I = Type2Number.find(STy);
602 if (I != Type2Number.end())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000603 OS << '%' << I->second;
604 else // Not enumerated, print the hex address.
Benjamin Kramer4e8b4632011-11-02 17:24:36 +0000605 OS << "%\"type " << STy << '\"';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000606 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000607 }
608 case Type::PointerTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000609 PointerType *PTy = cast<PointerType>(Ty);
610 print(PTy->getElementType(), OS);
Chris Lattner07d88292009-02-28 20:35:42 +0000611 if (unsigned AddressSpace = PTy->getAddressSpace())
Chris Lattner06a23212009-02-28 21:27:31 +0000612 OS << " addrspace(" << AddressSpace << ')';
613 OS << '*';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000614 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000615 }
616 case Type::ArrayTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000617 ArrayType *ATy = cast<ArrayType>(Ty);
Chris Lattner06a23212009-02-28 21:27:31 +0000618 OS << '[' << ATy->getNumElements() << " x ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000619 print(ATy->getElementType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000620 OS << ']';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000621 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000622 }
623 case Type::VectorTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000624 VectorType *PTy = cast<VectorType>(Ty);
Chris Lattner06a23212009-02-28 21:27:31 +0000625 OS << "<" << PTy->getNumElements() << " x ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000626 print(PTy->getElementType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000627 OS << '>';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000628 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000629 }
Chris Lattner0f578952009-02-28 20:25:14 +0000630 }
Rafael Espindolaba7df702013-12-07 02:27:52 +0000631 llvm_unreachable("Invalid TypeID");
Chris Lattner0f578952009-02-28 20:25:14 +0000632}
633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000634void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
635 if (STy->isOpaque()) {
636 OS << "opaque";
637 return;
Chris Lattner0f578952009-02-28 20:25:14 +0000638 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000639
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000640 if (STy->isPacked())
641 OS << '<';
Andrew Trickec4b6e72011-09-30 19:48:58 +0000642
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000643 if (STy->getNumElements() == 0) {
644 OS << "{}";
645 } else {
646 StructType::element_iterator I = STy->element_begin();
647 OS << "{ ";
648 print(*I++, OS);
649 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
650 OS << ", ";
651 print(*I, OS);
Chris Lattner3243ea12009-03-01 00:03:38 +0000652 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000654 OS << " }";
Chris Lattner92c5c122009-02-28 23:20:19 +0000655 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000656 if (STy->isPacked())
657 OS << '>';
Chris Lattner92c5c122009-02-28 23:20:19 +0000658}
659
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000660namespace llvm {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000661
Chris Lattner3eee99c2008-08-19 04:36:02 +0000662//===----------------------------------------------------------------------===//
663// SlotTracker Class: Enumerate slot numbers for unnamed values
664//===----------------------------------------------------------------------===//
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000665/// This class provides computation of slot numbers for LLVM Assembly writing.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000666///
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000667class SlotTracker {
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000668public:
Devang Patel983c6b12009-07-08 21:44:25 +0000669 /// ValueMap - A mapping of Values to slot numbers.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000670 using ValueMap = DenseMap<const Value *, unsigned>;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
672private:
Devang Patel983c6b12009-07-08 21:44:25 +0000673 /// TheModule - The module for which we are holding slot numbers.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000674 const Module* TheModule;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675
Devang Patel983c6b12009-07-08 21:44:25 +0000676 /// TheFunction - The function for which we are holding slot numbers.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000677 const Function* TheFunction = nullptr;
678 bool FunctionProcessed = false;
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000679 bool ShouldInitializeAllMetadata;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000680
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000681 /// The summary index for which we are holding slot numbers.
682 const ModuleSummaryIndex *TheIndex = nullptr;
683
Jay Foaddbb221d2011-07-11 07:28:49 +0000684 /// mMap - The slot map for the module level data.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000685 ValueMap mMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000686 unsigned mNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Jay Foaddbb221d2011-07-11 07:28:49 +0000688 /// fMap - The slot map for the function level data.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000689 ValueMap fMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000690 unsigned fNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Devang Patel983c6b12009-07-08 21:44:25 +0000692 /// mdnMap - Map for MDNodes.
Chris Lattnercf4a76e2009-12-31 02:20:11 +0000693 DenseMap<const MDNode*, unsigned> mdnMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000694 unsigned mdnNext = 0;
Bill Wendling829b4782013-02-11 08:43:33 +0000695
696 /// asMap - The slot map for attribute sets.
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000697 DenseMap<AttributeSet, unsigned> asMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000698 unsigned asNext = 0;
699
Teresa Johnson8fc76662018-07-02 22:09:23 +0000700 /// ModulePathMap - The slot map for Module paths used in the summary index.
701 StringMap<unsigned> ModulePathMap;
702 unsigned ModulePathNext = 0;
703
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000704 /// GUIDMap - The slot map for GUIDs used in the summary index.
705 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
706 unsigned GUIDNext = 0;
707
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000708 /// TypeIdMap - The slot map for type ids used in the summary index.
709 StringMap<unsigned> TypeIdMap;
710 unsigned TypeIdNext = 0;
711
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000712public:
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000713 /// Construct from a module.
714 ///
715 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
716 /// functions, giving correct numbering for metadata referenced only from
717 /// within a function (even if no functions have been initialized).
718 explicit SlotTracker(const Module *M,
719 bool ShouldInitializeAllMetadata = false);
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000720
Chris Lattner393b7cd2008-08-17 04:17:45 +0000721 /// Construct from a function, starting out in incorp state.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000722 ///
723 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
724 /// functions, giving correct numbering for metadata referenced only from
725 /// within a function (even if no functions have been initialized).
726 explicit SlotTracker(const Function *F,
727 bool ShouldInitializeAllMetadata = false);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000728
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000729 /// Construct from a module summary index.
730 explicit SlotTracker(const ModuleSummaryIndex *Index);
731
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000732 SlotTracker(const SlotTracker &) = delete;
733 SlotTracker &operator=(const SlotTracker &) = delete;
734
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000735 /// Return the slot number of the specified value in it's type
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000736 /// plane. If something is not in the SlotTracker, return -1.
Chris Lattner5e043322007-01-11 03:54:27 +0000737 int getLocalSlot(const Value *V);
738 int getGlobalSlot(const GlobalValue *V);
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000739 int getMetadataSlot(const MDNode *N);
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000740 int getAttributeGroupSlot(AttributeSet AS);
Teresa Johnson8fc76662018-07-02 22:09:23 +0000741 int getModulePathSlot(StringRef Path);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000742 int getGUIDSlot(GlobalValue::GUID GUID);
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000743 int getTypeIdSlot(StringRef Id);
Reid Spencer8beac692004-06-09 15:26:53 +0000744
Misha Brukmanb1c93172005-04-21 23:48:37 +0000745 /// If you'd like to deal with a function instead of just a module, use
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000746 /// this method to get its data into the SlotTracker.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000747 void incorporateFunction(const Function *F) {
748 TheFunction = F;
Reid Spencerb0ac8c42004-08-16 07:46:33 +0000749 FunctionProcessed = false;
750 }
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000751
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000752 const Function *getFunction() const { return TheFunction; }
753
Misha Brukmanb1c93172005-04-21 23:48:37 +0000754 /// After calling incorporateFunction, use this method to remove the
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000755 /// most recently incorporated function from the SlotTracker. This
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000756 /// will reset the state of the machine back to just the module contents.
757 void purgeFunction();
758
Devang Patel983c6b12009-07-08 21:44:25 +0000759 /// MDNode map iterators.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000760 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
761
Chris Lattnercf4a76e2009-12-31 02:20:11 +0000762 mdn_iterator mdn_begin() { return mdnMap.begin(); }
763 mdn_iterator mdn_end() { return mdnMap.end(); }
764 unsigned mdn_size() const { return mdnMap.size(); }
765 bool mdn_empty() const { return mdnMap.empty(); }
Devang Patel983c6b12009-07-08 21:44:25 +0000766
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000767 /// AttributeSet map iterators.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000768 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
769
Bill Wendling829b4782013-02-11 08:43:33 +0000770 as_iterator as_begin() { return asMap.begin(); }
771 as_iterator as_end() { return asMap.end(); }
772 unsigned as_size() const { return asMap.size(); }
773 bool as_empty() const { return asMap.empty(); }
774
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000775 /// GUID map iterators.
776 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
777
778 /// These functions do the actual initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000779 inline void initializeIfNeeded();
780 void initializeIndexIfNeeded();
Reid Spencer56010e42004-05-26 21:56:09 +0000781
Devang Patel983c6b12009-07-08 21:44:25 +0000782 // Implementation Details
783private:
Chris Lattnerea862a32007-01-09 07:55:49 +0000784 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
785 void CreateModuleSlot(const GlobalValue *V);
Devang Patel983c6b12009-07-08 21:44:25 +0000786
787 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000788 void CreateMetadataSlot(const MDNode *N);
Devang Patel983c6b12009-07-08 21:44:25 +0000789
Chris Lattnerea862a32007-01-09 07:55:49 +0000790 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
791 void CreateFunctionSlot(const Value *V);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000792
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000793 /// Insert the specified AttributeSet into the slot table.
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000794 void CreateAttributeSetSlot(AttributeSet AS);
Bill Wendling829b4782013-02-11 08:43:33 +0000795
Teresa Johnson8fc76662018-07-02 22:09:23 +0000796 inline void CreateModulePathSlot(StringRef Path);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000797 void CreateGUIDSlot(GlobalValue::GUID GUID);
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000798 void CreateTypeIdSlot(StringRef Id);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000799
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000800 /// Add all of the module level global variables (and their initializers)
801 /// and function declarations, but not the contents of those functions.
802 void processModule();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000803 void processIndex();
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000804
Devang Patel983c6b12009-07-08 21:44:25 +0000805 /// Add all of the functions arguments, basic blocks, and instructions.
Reid Spencer56010e42004-05-26 21:56:09 +0000806 void processFunction();
807
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000808 /// Add the metadata directly attached to a GlobalObject.
809 void processGlobalObjectMetadata(const GlobalObject &GO);
810
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000811 /// Add all of the metadata from a function.
812 void processFunctionMetadata(const Function &F);
813
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +0000814 /// Add all of the metadata from an instruction.
815 void processInstructionMetadata(const Instruction &I);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000816};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000817
818} // end namespace llvm
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000819
820ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
821 const Function *F)
822 : M(M), F(F), Machine(&Machine) {}
823
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +0000824ModuleSlotTracker::ModuleSlotTracker(const Module *M,
825 bool ShouldInitializeAllMetadata)
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000826 : ShouldCreateStorage(M),
827 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000828
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000829ModuleSlotTracker::~ModuleSlotTracker() = default;
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000830
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000831SlotTracker *ModuleSlotTracker::getMachine() {
832 if (!ShouldCreateStorage)
833 return Machine;
834
835 ShouldCreateStorage = false;
836 MachineStorage =
837 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
838 Machine = MachineStorage.get();
839 return Machine;
840}
841
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000842void ModuleSlotTracker::incorporateFunction(const Function &F) {
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000843 // Using getMachine() may lazily create the slot tracker.
844 if (!getMachine())
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000845 return;
846
847 // Nothing to do if this is the right function already.
848 if (this->F == &F)
849 return;
850 if (this->F)
851 Machine->purgeFunction();
852 Machine->incorporateFunction(&F);
853 this->F = &F;
854}
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000855
Alex Lorenz991a6242015-07-27 22:31:04 +0000856int ModuleSlotTracker::getLocalSlot(const Value *V) {
857 assert(F && "No function incorporated");
858 return Machine->getLocalSlot(V);
859}
860
Chris Lattner3eee99c2008-08-19 04:36:02 +0000861static SlotTracker *createSlotTracker(const Value *V) {
862 if (const Argument *FA = dyn_cast<Argument>(V))
863 return new SlotTracker(FA->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
Chris Lattner3eee99c2008-08-19 04:36:02 +0000865 if (const Instruction *I = dyn_cast<Instruction>(V))
Andrew Trick2f0cbf62011-09-30 19:50:40 +0000866 if (I->getParent())
867 return new SlotTracker(I->getParent()->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000868
Chris Lattner3eee99c2008-08-19 04:36:02 +0000869 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
870 return new SlotTracker(BB->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000871
Chris Lattner3eee99c2008-08-19 04:36:02 +0000872 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
873 return new SlotTracker(GV->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000874
Chris Lattner3eee99c2008-08-19 04:36:02 +0000875 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000876 return new SlotTracker(GA->getParent());
877
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000878 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
879 return new SlotTracker(GIF->getParent());
880
Chris Lattner3eee99c2008-08-19 04:36:02 +0000881 if (const Function *Func = dyn_cast<Function>(V))
882 return new SlotTracker(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000883
Craig Topperc6207612014-04-09 06:08:46 +0000884 return nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000885}
886
887#if 0
David Greenec7f9b122010-01-05 01:29:26 +0000888#define ST_DEBUG(X) dbgs() << X
Chris Lattner3eee99c2008-08-19 04:36:02 +0000889#else
Chris Lattner604e3512008-08-19 04:47:09 +0000890#define ST_DEBUG(X)
Chris Lattner3eee99c2008-08-19 04:36:02 +0000891#endif
892
893// Module level constructor. Causes the contents of the Module (sans functions)
894// to be added to the slot table.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000895SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000896 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
Chris Lattner3eee99c2008-08-19 04:36:02 +0000897
898// Function level constructor. Causes the contents of the Module and the one
899// function provided to be added to the slot table.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000900SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000901 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000902 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
Chris Lattner3eee99c2008-08-19 04:36:02 +0000903
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000904SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
905 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
906
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000907inline void SlotTracker::initializeIfNeeded() {
Chris Lattner3eee99c2008-08-19 04:36:02 +0000908 if (TheModule) {
909 processModule();
Craig Topperc6207612014-04-09 06:08:46 +0000910 TheModule = nullptr; ///< Prevent re-processing next time we're called.
Chris Lattner3eee99c2008-08-19 04:36:02 +0000911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Chris Lattner3eee99c2008-08-19 04:36:02 +0000913 if (TheFunction && !FunctionProcessed)
914 processFunction();
915}
916
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000917void SlotTracker::initializeIndexIfNeeded() {
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000918 if (!TheIndex)
919 return;
920 processIndex();
921 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
922}
923
Chris Lattner3eee99c2008-08-19 04:36:02 +0000924// Iterate through all the global variables, functions, and global
925// variable initializers and create slots for them.
926void SlotTracker::processModule() {
Chris Lattner604e3512008-08-19 04:47:09 +0000927 ST_DEBUG("begin processModule!\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000928
Chris Lattner3eee99c2008-08-19 04:36:02 +0000929 // Add all of the unnamed global variables to the value table.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000930 for (const GlobalVariable &Var : TheModule->globals()) {
931 if (!Var.hasName())
932 CreateModuleSlot(&Var);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000933 processGlobalObjectMetadata(Var);
Javed Absarf3d79042017-05-11 12:28:08 +0000934 auto Attrs = Var.getAttributes();
935 if (Attrs.hasAttributes())
936 CreateAttributeSetSlot(Attrs);
Devang Patel983c6b12009-07-08 21:44:25 +0000937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Rafael Espindola54fc2982015-06-17 17:53:31 +0000939 for (const GlobalAlias &A : TheModule->aliases()) {
940 if (!A.hasName())
941 CreateModuleSlot(&A);
942 }
943
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000944 for (const GlobalIFunc &I : TheModule->ifuncs()) {
945 if (!I.hasName())
946 CreateModuleSlot(&I);
947 }
948
Devang Patel23e68302009-07-29 22:04:47 +0000949 // Add metadata used by named metadata.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000950 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
951 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
952 CreateMetadataSlot(NMD.getOperand(i));
Devang Patel23e68302009-07-29 22:04:47 +0000953 }
954
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000955 for (const Function &F : *TheModule) {
956 if (!F.hasName())
Bill Wendling829b4782013-02-11 08:43:33 +0000957 // Add all the unnamed functions to the table.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000958 CreateModuleSlot(&F);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000959
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000960 if (ShouldInitializeAllMetadata)
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000961 processFunctionMetadata(F);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000962
Bill Wendling829b4782013-02-11 08:43:33 +0000963 // Add all the function attributes to the table.
Bill Wendling90bc19c2013-02-20 07:21:42 +0000964 // FIXME: Add attributes of other objects?
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000965 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
966 if (FnAttrs.hasAttributes())
Bill Wendling829b4782013-02-11 08:43:33 +0000967 CreateAttributeSetSlot(FnAttrs);
968 }
969
Chris Lattner604e3512008-08-19 04:47:09 +0000970 ST_DEBUG("end processModule!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +0000971}
972
Chris Lattner3eee99c2008-08-19 04:36:02 +0000973// Process the arguments, basic blocks, and instructions of a function.
974void SlotTracker::processFunction() {
Chris Lattner604e3512008-08-19 04:47:09 +0000975 ST_DEBUG("begin processFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +0000976 fNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000977
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +0000978 // Process function metadata if it wasn't hit at the module-level.
979 if (!ShouldInitializeAllMetadata)
980 processFunctionMetadata(*TheFunction);
981
Chris Lattner3eee99c2008-08-19 04:36:02 +0000982 // Add all the function arguments with no names.
983 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
984 AE = TheFunction->arg_end(); AI != AE; ++AI)
985 if (!AI->hasName())
Duncan P. N. Exon Smith52888a62015-10-08 23:49:46 +0000986 CreateFunctionSlot(&*AI);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000987
Chris Lattner604e3512008-08-19 04:47:09 +0000988 ST_DEBUG("Inserting Instructions:\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000989
Chris Lattner3eee99c2008-08-19 04:36:02 +0000990 // Add all of the basic blocks and instructions with no names.
Duncan P. N. Exon Smith27f33ee2015-03-14 19:44:01 +0000991 for (auto &BB : *TheFunction) {
992 if (!BB.hasName())
993 CreateFunctionSlot(&BB);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000994
Duncan P. N. Exon Smith27f33ee2015-03-14 19:44:01 +0000995 for (auto &I : BB) {
996 if (!I.getType()->isVoidTy() && !I.hasName())
997 CreateFunctionSlot(&I);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000998
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +0000999 // We allow direct calls to any llvm.foo function here, because the
1000 // target may not be linked into the optimizer.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001001 if (auto CS = ImmutableCallSite(&I)) {
Bill Wendlinga0323742013-02-22 09:09:42 +00001002 // Add all the call attributes to the table.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001003 AttributeSet Attrs = CS.getAttributes().getFnAttributes();
1004 if (Attrs.hasAttributes())
Bill Wendlinga0323742013-02-22 09:09:42 +00001005 CreateAttributeSetSlot(Attrs);
Chris Lattner58aff8f2010-05-10 20:53:17 +00001006 }
Devang Patel983c6b12009-07-08 21:44:25 +00001007 }
Chris Lattner3eee99c2008-08-19 04:36:02 +00001008 }
Devang Pateldec23fd2009-09-16 20:21:17 +00001009
Chris Lattner3eee99c2008-08-19 04:36:02 +00001010 FunctionProcessed = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001011
Chris Lattner604e3512008-08-19 04:47:09 +00001012 ST_DEBUG("end processFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001013}
1014
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001015// Iterate through all the GUID in the index and create slots for them.
1016void SlotTracker::processIndex() {
1017 ST_DEBUG("begin processIndex!\n");
1018 assert(TheIndex);
1019
1020 // The first block of slots are just the module ids, which start at 0 and are
Teresa Johnson8fc76662018-07-02 22:09:23 +00001021 // assigned consecutively. Since the StringMap iteration order isn't
1022 // guaranteed, use a std::map to order by module ID before assigning slots.
1023 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1024 for (auto &ModPath : TheIndex->modulePaths())
1025 ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1026 for (auto &ModPair : ModuleIdToPathMap)
1027 CreateModulePathSlot(ModPair.second);
1028
1029 // Start numbering the GUIDs after the module ids.
1030 GUIDNext = ModulePathNext;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001031
1032 for (auto &GlobalList : *TheIndex)
1033 CreateGUIDSlot(GlobalList.first);
1034
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001035 // Start numbering the TypeIds after the GUIDs.
1036 TypeIdNext = GUIDNext;
1037
1038 for (auto TidIter = TheIndex->typeIds().begin();
1039 TidIter != TheIndex->typeIds().end(); TidIter++)
1040 CreateTypeIdSlot(TidIter->second.first);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001041
1042 ST_DEBUG("end processIndex!\n");
1043}
1044
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001045void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001046 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001047 GO.getAllMetadata(MDs);
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +00001048 for (auto &MD : MDs)
1049 CreateMetadataSlot(MD.second);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001050}
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001051
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001052void SlotTracker::processFunctionMetadata(const Function &F) {
1053 processGlobalObjectMetadata(F);
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +00001054 for (auto &BB : F) {
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00001055 for (auto &I : BB)
1056 processInstructionMetadata(I);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001057 }
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00001058}
1059
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +00001060void SlotTracker::processInstructionMetadata(const Instruction &I) {
1061 // Process metadata used directly by intrinsics.
1062 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1063 if (Function *F = CI->getCalledFunction())
Justin Lebar9cbc3012016-07-28 23:58:15 +00001064 if (F->isIntrinsic())
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +00001065 for (auto &Op : I.operands())
1066 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1067 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1068 CreateMetadataSlot(N);
1069
1070 // Process metadata attached to this instruction.
1071 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1072 I.getAllMetadata(MDs);
1073 for (auto &MD : MDs)
1074 CreateMetadataSlot(MD.second);
1075}
1076
Chris Lattner3eee99c2008-08-19 04:36:02 +00001077/// Clean up after incorporating a function. This is the only way to get out of
1078/// the function incorporation state that affects get*Slot/Create*Slot. Function
1079/// incorporation state is indicated by TheFunction != 0.
1080void SlotTracker::purgeFunction() {
Chris Lattner604e3512008-08-19 04:47:09 +00001081 ST_DEBUG("begin purgeFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001082 fMap.clear(); // Simply discard the function level map
Craig Topperc6207612014-04-09 06:08:46 +00001083 TheFunction = nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001084 FunctionProcessed = false;
Chris Lattner604e3512008-08-19 04:47:09 +00001085 ST_DEBUG("end purgeFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001086}
1087
1088/// getGlobalSlot - Get the slot number of a global value.
1089int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1090 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001091 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Jay Foaddbb221d2011-07-11 07:28:49 +00001093 // Find the value in the module map
Chris Lattner3eee99c2008-08-19 04:36:02 +00001094 ValueMap::iterator MI = mMap.find(V);
Dan Gohman1dd27572008-10-01 19:58:59 +00001095 return MI == mMap.end() ? -1 : (int)MI->second;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001096}
1097
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001098/// getMetadataSlot - Get the slot number of a MDNode.
1099int SlotTracker::getMetadataSlot(const MDNode *N) {
Devang Patel983c6b12009-07-08 21:44:25 +00001100 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001101 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001102
Jay Foaddbb221d2011-07-11 07:28:49 +00001103 // Find the MDNode in the module map
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001104 mdn_iterator MI = mdnMap.find(N);
Devang Patel983c6b12009-07-08 21:44:25 +00001105 return MI == mdnMap.end() ? -1 : (int)MI->second;
1106}
1107
Chris Lattner3eee99c2008-08-19 04:36:02 +00001108/// getLocalSlot - Get the slot number for a value that is local to a function.
1109int SlotTracker::getLocalSlot(const Value *V) {
1110 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001111
Chris Lattner3eee99c2008-08-19 04:36:02 +00001112 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001113 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001114
Chris Lattner3eee99c2008-08-19 04:36:02 +00001115 ValueMap::iterator FI = fMap.find(V);
Dan Gohman1dd27572008-10-01 19:58:59 +00001116 return FI == fMap.end() ? -1 : (int)FI->second;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001117}
1118
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001119int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
Bill Wendling829b4782013-02-11 08:43:33 +00001120 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001121 initializeIfNeeded();
Bill Wendling829b4782013-02-11 08:43:33 +00001122
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001123 // Find the AttributeSet in the module map.
Bill Wendling829b4782013-02-11 08:43:33 +00001124 as_iterator AI = asMap.find(AS);
1125 return AI == asMap.end() ? -1 : (int)AI->second;
1126}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001127
Teresa Johnson8fc76662018-07-02 22:09:23 +00001128int SlotTracker::getModulePathSlot(StringRef Path) {
1129 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001130 initializeIndexIfNeeded();
Teresa Johnson8fc76662018-07-02 22:09:23 +00001131
1132 // Find the Module path in the map
1133 auto I = ModulePathMap.find(Path);
1134 return I == ModulePathMap.end() ? -1 : (int)I->second;
1135}
1136
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001137int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1138 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001139 initializeIndexIfNeeded();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001140
1141 // Find the GUID in the map
1142 guid_iterator I = GUIDMap.find(GUID);
1143 return I == GUIDMap.end() ? -1 : (int)I->second;
1144}
1145
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001146int SlotTracker::getTypeIdSlot(StringRef Id) {
1147 // Check for uninitialized state and do lazy initialization.
1148 initializeIndexIfNeeded();
1149
1150 // Find the TypeId string in the map
1151 auto I = TypeIdMap.find(Id);
1152 return I == TypeIdMap.end() ? -1 : (int)I->second;
1153}
1154
Chris Lattner3eee99c2008-08-19 04:36:02 +00001155/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1156void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1157 assert(V && "Can't insert a null Value into SlotTracker!");
Chris Lattner031560c2009-12-29 07:25:48 +00001158 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001159 assert(!V->hasName() && "Doesn't need a slot!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001160
Chris Lattner3eee99c2008-08-19 04:36:02 +00001161 unsigned DestSlot = mNext++;
1162 mMap[V] = DestSlot;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattner604e3512008-08-19 04:47:09 +00001164 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
Chris Lattner3eee99c2008-08-19 04:36:02 +00001165 DestSlot << " [");
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001166 // G = Global, F = Function, A = Alias, I = IFunc, o = other
Chris Lattner604e3512008-08-19 04:47:09 +00001167 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
Chris Lattner3eee99c2008-08-19 04:36:02 +00001168 (isa<Function>(V) ? 'F' :
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001169 (isa<GlobalAlias>(V) ? 'A' :
1170 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001171}
1172
Chris Lattner3eee99c2008-08-19 04:36:02 +00001173/// CreateSlot - Create a new slot for the specified value if it has no name.
1174void SlotTracker::CreateFunctionSlot(const Value *V) {
Chris Lattner031560c2009-12-29 07:25:48 +00001175 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001176
Chris Lattner3eee99c2008-08-19 04:36:02 +00001177 unsigned DestSlot = fNext++;
1178 fMap[V] = DestSlot;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001179
Chris Lattner3eee99c2008-08-19 04:36:02 +00001180 // G = Global, F = Function, o = other
Chris Lattner604e3512008-08-19 04:47:09 +00001181 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
Chris Lattner3eee99c2008-08-19 04:36:02 +00001182 DestSlot << " [o]\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001183}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001184
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001185/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1186void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1187 assert(N && "Can't insert a null Value into SlotTracker!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001188
Reid Kleckner6d353342017-08-23 20:31:27 +00001189 // Don't make slots for DIExpressions. We just print them inline everywhere.
1190 if (isa<DIExpression>(N))
1191 return;
1192
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001193 unsigned DestSlot = mdnNext;
1194 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1195 return;
1196 ++mdnNext;
Devang Patel983c6b12009-07-08 21:44:25 +00001197
Chris Lattner0d50bdd2009-12-31 02:27:30 +00001198 // Recursively add any MDNodes referenced by operands.
1199 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1200 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1201 CreateMetadataSlot(Op);
Devang Patel983c6b12009-07-08 21:44:25 +00001202}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001203
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001204void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1205 assert(AS.hasAttributes() && "Doesn't need a slot!");
Bill Wendling829b4782013-02-11 08:43:33 +00001206
1207 as_iterator I = asMap.find(AS);
1208 if (I != asMap.end())
1209 return;
1210
1211 unsigned DestSlot = asNext++;
1212 asMap[AS] = DestSlot;
1213}
1214
Teresa Johnson8fc76662018-07-02 22:09:23 +00001215/// Create a new slot for the specified Module
1216void SlotTracker::CreateModulePathSlot(StringRef Path) {
1217 ModulePathMap[Path] = ModulePathNext++;
1218}
1219
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001220/// Create a new slot for the specified GUID
1221void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1222 GUIDMap[GUID] = GUIDNext++;
1223}
1224
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001225/// Create a new slot for the specified Id
1226void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1227 TypeIdMap[Id] = TypeIdNext++;
1228}
1229
Chris Lattner3eee99c2008-08-19 04:36:02 +00001230//===----------------------------------------------------------------------===//
1231// AsmWriter Implementation
1232//===----------------------------------------------------------------------===//
Chris Lattner7f8845a2002-07-23 18:07:49 +00001233
Dan Gohman12dad632009-08-12 20:56:03 +00001234static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
Dan Gohman8061d9e2009-08-13 15:27:57 +00001235 TypePrinting *TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00001236 SlotTracker *Machine,
1237 const Module *Context);
Reid Spencer58d30f22004-07-04 11:50:43 +00001238
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001239static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1240 TypePrinting *TypePrinter,
1241 SlotTracker *Machine, const Module *Context,
1242 bool FromValue = false);
1243
Dan Gohman12dad632009-08-12 20:56:03 +00001244static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
Michael Ilseman92053172012-11-27 00:42:44 +00001245 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001246 // 'Fast' is an abbreviation for all fast-math-flags.
1247 if (FPO->isFast())
Michael Ilseman92053172012-11-27 00:42:44 +00001248 Out << " fast";
1249 else {
Sanjay Patel629c4112017-11-06 16:27:15 +00001250 if (FPO->hasAllowReassoc())
1251 Out << " reassoc";
Michael Ilseman92053172012-11-27 00:42:44 +00001252 if (FPO->hasNoNaNs())
1253 Out << " nnan";
1254 if (FPO->hasNoInfs())
1255 Out << " ninf";
1256 if (FPO->hasNoSignedZeros())
1257 Out << " nsz";
1258 if (FPO->hasAllowReciprocal())
1259 Out << " arcp";
Adam Nemetcd847a82017-03-28 20:11:52 +00001260 if (FPO->hasAllowContract())
1261 Out << " contract";
Sanjay Patel629c4112017-11-06 16:27:15 +00001262 if (FPO->hasApproxFunc())
1263 Out << " afn";
Michael Ilseman92053172012-11-27 00:42:44 +00001264 }
1265 }
1266
Dan Gohman0ebd6962009-07-20 21:19:07 +00001267 if (const OverflowingBinaryOperator *OBO =
1268 dyn_cast<OverflowingBinaryOperator>(U)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001269 if (OBO->hasNoUnsignedWrap())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001270 Out << " nuw";
Dan Gohman16f54152009-08-20 17:11:38 +00001271 if (OBO->hasNoSignedWrap())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001272 Out << " nsw";
Chris Lattner35315d02011-02-06 21:44:57 +00001273 } else if (const PossiblyExactOperator *Div =
1274 dyn_cast<PossiblyExactOperator>(U)) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001275 if (Div->isExact())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001276 Out << " exact";
Dan Gohman1639c392009-07-27 21:53:46 +00001277 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1278 if (GEP->isInBounds())
1279 Out << " inbounds";
Dan Gohman0ebd6962009-07-20 21:19:07 +00001280 }
1281}
1282
Dan Gohmanefb8dbb2010-07-14 20:57:55 +00001283static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1284 TypePrinting &TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00001285 SlotTracker *Machine,
1286 const Module *Context) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001287 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001288 if (CI->getType()->isIntegerTy(1)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001289 Out << (CI->getZExtValue() ? "true" : "false");
Chris Lattner17f71652008-08-17 07:19:36 +00001290 return;
1291 }
1292 Out << CI->getValue();
1293 return;
1294 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001295
Chris Lattner17f71652008-08-17 07:19:36 +00001296 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001297 const APFloat &APF = CFP->getValueAPF();
1298 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1299 &APF.getSemantics() == &APFloat::IEEEdouble()) {
Dale Johannesen028084e2007-09-12 03:30:33 +00001300 // We would like to output the FP constant value in exponential notation,
1301 // but we cannot do this if doing so will lose precision. Check here to
1302 // make sure that we only output it in exponential format if we can parse
1303 // the value back and get the same value.
1304 //
Dale Johannesen1f864982009-01-21 20:32:55 +00001305 bool ignored;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001306 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1307 bool isInf = APF.isInfinity();
1308 bool isNaN = APF.isNaN();
Justin Bognerb609b6b2015-12-04 01:14:24 +00001309 if (!isInf && !isNaN) {
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001310 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
Dan Gohman518cda42011-12-17 00:04:22 +00001311 SmallString<128> StrVal;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001312 APF.toString(StrVal, 6, 0, false);
Dan Gohman518cda42011-12-17 00:04:22 +00001313 // Check to make sure that the stringized number is not some string like
1314 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1315 // that the string matches the "[-+]?[0-9]" regex.
1316 //
Serguei Katkovc9a752c2017-04-21 06:14:38 +00001317 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1318 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1319 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1320 "[-+]?[0-9] regex does not match!");
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001321 // Reparse stringized version!
1322 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1323 Out << StrVal;
1324 return;
Dale Johannesen028084e2007-09-12 03:30:33 +00001325 }
Chris Lattner1e194682002-04-18 18:53:13 +00001326 }
Dale Johannesen028084e2007-09-12 03:30:33 +00001327 // Otherwise we could not reparse it to exactly the same value, so we must
Dale Johannesen1f864982009-01-21 20:32:55 +00001328 // output the string in hexadecimal format! Note that loading and storing
1329 // floating point types changes the bits of NaNs on some hosts, notably
1330 // x86, so we must not use these types.
Benjamin Kramer86c77412014-03-15 18:47:07 +00001331 static_assert(sizeof(double) == sizeof(uint64_t),
1332 "assuming that double is 64 bits!");
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001333 APFloat apf = APF;
Justin Bognerb609b6b2015-12-04 01:14:24 +00001334 // Floats are represented in ASCII IR as double, convert.
Dale Johannesen1f864982009-01-21 20:32:55 +00001335 if (!isDouble)
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001336 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
Dale Johannesen1f864982009-01-21 20:32:55 +00001337 &ignored);
Justin Bogner93289572015-12-04 02:14:34 +00001338 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001339 return;
1340 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001341
Tobias Grosser6b31d172012-05-24 15:59:06 +00001342 // Either half, or some form of long double.
1343 // These appear as a magic letter identifying the type, then a
1344 // fixed number of hex digits.
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001345 Out << "0x";
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001346 APInt API = APF.bitcastToAPInt();
1347 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001348 Out << 'K';
Justin Bogner93289572015-12-04 02:14:34 +00001349 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1350 /*Upper=*/true);
1351 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1352 /*Upper=*/true);
Dale Johannesen93eefa02009-03-23 21:16:53 +00001353 return;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001354 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001355 Out << 'L';
Justin Bogner93289572015-12-04 02:14:34 +00001356 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1357 /*Upper=*/true);
1358 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1359 /*Upper=*/true);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001360 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001361 Out << 'M';
Justin Bogner93289572015-12-04 02:14:34 +00001362 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1363 /*Upper=*/true);
1364 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1365 /*Upper=*/true);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001366 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
Tobias Grosser6b31d172012-05-24 15:59:06 +00001367 Out << 'H';
Justin Bogner93289572015-12-04 02:14:34 +00001368 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1369 /*Upper=*/true);
Tobias Grosser6b31d172012-05-24 15:59:06 +00001370 } else
Torok Edwinfbcc6632009-07-14 16:55:14 +00001371 llvm_unreachable("Unsupported floating point type");
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001372 return;
1373 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001374
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001375 if (isa<ConstantAggregateZero>(CV)) {
Chris Lattner76b2ff42004-02-15 05:55:15 +00001376 Out << "zeroinitializer";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001377 return;
1378 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00001379
Chris Lattner214cc702009-10-28 03:38:12 +00001380 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1381 Out << "blockaddress(";
Dan Gohmana2489d12010-07-20 23:55:01 +00001382 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1383 Context);
Chris Lattner214cc702009-10-28 03:38:12 +00001384 Out << ", ";
Dan Gohmana2489d12010-07-20 23:55:01 +00001385 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1386 Context);
Chris Lattner214cc702009-10-28 03:38:12 +00001387 Out << ")";
1388 return;
1389 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001390
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001391 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001392 Type *ETy = CA->getType()->getElementType();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001393 Out << '[';
1394 TypePrinter.print(ETy, Out);
1395 Out << ' ';
1396 WriteAsOperandInternal(Out, CA->getOperand(0),
1397 &TypePrinter, Machine,
1398 Context);
1399 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1400 Out << ", ";
Chris Lattner9c181f62012-01-31 03:15:40 +00001401 TypePrinter.print(ETy, Out);
1402 Out << ' ';
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001403 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
Chris Lattner9c181f62012-01-31 03:15:40 +00001404 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001405 }
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001406 Out << ']';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001407 return;
1408 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001409
Chris Lattnerfa775002012-01-26 02:32:04 +00001410 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1411 // As a special case, print the array as a string if it is an array of
1412 // i8 with ConstantInt values.
1413 if (CA->isString()) {
1414 Out << "c\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00001415 printEscapedString(CA->getAsString(), Out);
Chris Lattnerfa775002012-01-26 02:32:04 +00001416 Out << '"';
1417 return;
1418 }
1419
1420 Type *ETy = CA->getType()->getElementType();
1421 Out << '[';
Chris Lattner9c181f62012-01-31 03:15:40 +00001422 TypePrinter.print(ETy, Out);
1423 Out << ' ';
1424 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1425 &TypePrinter, Machine,
1426 Context);
1427 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1428 Out << ", ";
Chris Lattnerfa775002012-01-26 02:32:04 +00001429 TypePrinter.print(ETy, Out);
1430 Out << ' ';
Chris Lattner9c181f62012-01-31 03:15:40 +00001431 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1432 Machine, Context);
Chris Lattnerfa775002012-01-26 02:32:04 +00001433 }
Chris Lattner9c181f62012-01-31 03:15:40 +00001434 Out << ']';
Chris Lattnerfa775002012-01-26 02:32:04 +00001435 return;
1436 }
1437
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001438 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
Andrew Lenharth0d124b82007-01-08 18:21:30 +00001439 if (CS->getType()->isPacked())
1440 Out << '<';
Misha Brukman21bbdb92004-06-04 21:11:51 +00001441 Out << '{';
Jim Laskey3bb78742006-02-25 12:27:03 +00001442 unsigned N = CS->getNumOperands();
1443 if (N) {
Chris Lattner604e3512008-08-19 04:47:09 +00001444 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00001445 TypePrinter.print(CS->getOperand(0)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001446 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001447
Dan Gohmana2489d12010-07-20 23:55:01 +00001448 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1449 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001450
Jim Laskey3bb78742006-02-25 12:27:03 +00001451 for (unsigned i = 1; i < N; i++) {
Chris Lattnerd84bb632002-04-16 21:36:08 +00001452 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00001453 TypePrinter.print(CS->getOperand(i)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001454 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001455
Dan Gohmana2489d12010-07-20 23:55:01 +00001456 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1457 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001458 }
Dan Gohman81313fd2008-09-14 17:21:12 +00001459 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001460 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001461
Dan Gohman81313fd2008-09-14 17:21:12 +00001462 Out << '}';
Andrew Lenharth0d124b82007-01-08 18:21:30 +00001463 if (CS->getType()->isPacked())
1464 Out << '>';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001465 return;
1466 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001467
Chris Lattnerfa775002012-01-26 02:32:04 +00001468 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1469 Type *ETy = CV->getType()->getVectorElementType();
Dan Gohman1262a252009-02-11 00:25:25 +00001470 Out << '<';
Chris Lattnere101c442009-02-28 21:26:53 +00001471 TypePrinter.print(ETy, Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001472 Out << ' ';
Chris Lattnerfa775002012-01-26 02:32:04 +00001473 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1474 Machine, Context);
1475 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
Chris Lattner585297e82008-08-19 05:26:17 +00001476 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00001477 TypePrinter.print(ETy, Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001478 Out << ' ';
Chris Lattnerfa775002012-01-26 02:32:04 +00001479 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1480 Machine, Context);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001481 }
Dan Gohman1262a252009-02-11 00:25:25 +00001482 Out << '>';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001483 return;
1484 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001485
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001486 if (isa<ConstantPointerNull>(CV)) {
Chris Lattnerd84bb632002-04-16 21:36:08 +00001487 Out << "null";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001488 return;
1489 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001490
David Majnemerf0f224d2015-11-11 21:57:16 +00001491 if (isa<ConstantTokenNone>(CV)) {
1492 Out << "none";
1493 return;
1494 }
1495
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001496 if (isa<UndefValue>(CV)) {
Chris Lattner5e0b9f22004-10-16 18:08:06 +00001497 Out << "undef";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001498 return;
1499 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001500
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001501 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencer812a1be2006-12-04 05:19:18 +00001502 Out << CE->getOpcodeName();
Dan Gohman9c7f8082009-07-27 16:11:46 +00001503 WriteOptimizationInfo(Out, CE);
Reid Spencer812a1be2006-12-04 05:19:18 +00001504 if (CE->isCompare())
Tim Northoverde3aea0412016-08-17 20:25:25 +00001505 Out << ' ' << CmpInst::getPredicateName(
1506 static_cast<CmpInst::Predicate>(CE->getPredicate()));
Reid Spencer812a1be2006-12-04 05:19:18 +00001507 Out << " (";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001508
Peter Collingbourned93620b2016-11-10 22:34:55 +00001509 Optional<unsigned> InRangeOp;
David Blaikief72d05b2015-03-13 18:20:45 +00001510 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
David Blaikied06654f2015-07-29 20:26:23 +00001511 TypePrinter.print(GEP->getSourceElementType(), Out);
David Blaikief72d05b2015-03-13 18:20:45 +00001512 Out << ", ";
Peter Collingbourned93620b2016-11-10 22:34:55 +00001513 InRangeOp = GEP->getInRangeIndex();
1514 if (InRangeOp)
1515 ++*InRangeOp;
David Blaikief72d05b2015-03-13 18:20:45 +00001516 }
1517
Vikram S. Adveb952b542002-07-14 23:14:45 +00001518 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
Zachary Turner804d5022016-11-11 23:58:11 +00001519 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
Peter Collingbourned93620b2016-11-10 22:34:55 +00001520 Out << "inrange ";
Chris Lattnere101c442009-02-28 21:26:53 +00001521 TypePrinter.print((*OI)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001522 Out << ' ';
Dan Gohmana2489d12010-07-20 23:55:01 +00001523 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
Vikram S. Adveb952b542002-07-14 23:14:45 +00001524 if (OI+1 != CE->op_end())
Chris Lattner3cd8c562002-07-30 18:54:25 +00001525 Out << ", ";
Vikram S. Adveb952b542002-07-14 23:14:45 +00001526 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001527
Dan Gohmana76f0f72008-05-31 19:12:39 +00001528 if (CE->hasIndices()) {
Jay Foad0091fe82011-04-13 15:22:40 +00001529 ArrayRef<unsigned> Indices = CE->getIndices();
Dan Gohmana76f0f72008-05-31 19:12:39 +00001530 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1531 Out << ", " << Indices[i];
1532 }
1533
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001534 if (CE->isCast()) {
Chris Lattner83b396b2002-08-15 19:37:43 +00001535 Out << " to ";
Chris Lattnere101c442009-02-28 21:26:53 +00001536 TypePrinter.print(CE->getType(), Out);
Chris Lattner83b396b2002-08-15 19:37:43 +00001537 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001538
Misha Brukman21bbdb92004-06-04 21:11:51 +00001539 Out << ')';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001540 return;
Chris Lattnerd84bb632002-04-16 21:36:08 +00001541 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001542
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001543 Out << "<placeholder or erroneous Constant>";
Chris Lattnerd84bb632002-04-16 21:36:08 +00001544}
1545
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00001546static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1547 TypePrinting *TypePrinter, SlotTracker *Machine,
1548 const Module *Context) {
Chris Lattnercdec5812009-12-31 02:31:59 +00001549 Out << "!{";
1550 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001551 const Metadata *MD = Node->getOperand(mi);
1552 if (!MD)
Chris Lattnercdec5812009-12-31 02:31:59 +00001553 Out << "null";
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001554 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1555 Value *V = MDV->getValue();
Chris Lattnercdec5812009-12-31 02:31:59 +00001556 TypePrinter->print(V->getType(), Out);
1557 Out << ' ';
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001558 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1559 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001560 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
Chris Lattnercdec5812009-12-31 02:31:59 +00001561 }
1562 if (mi + 1 != me)
1563 Out << ", ";
1564 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00001565
Chris Lattnercdec5812009-12-31 02:31:59 +00001566 Out << "}";
1567}
1568
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001569namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001570
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001571struct FieldSeparator {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001572 bool Skip = true;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00001573 const char *Sep;
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001574
1575 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001576};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001577
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001578raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1579 if (FS.Skip) {
1580 FS.Skip = false;
1581 return OS;
1582 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00001583 return OS << FS.Sep;
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001584}
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001585
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001586struct MDFieldPrinter {
1587 raw_ostream &Out;
1588 FieldSeparator FS;
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001589 TypePrinting *TypePrinter = nullptr;
1590 SlotTracker *Machine = nullptr;
1591 const Module *Context = nullptr;
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001592
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001593 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001594 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1595 SlotTracker *Machine, const Module *Context)
1596 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1597 }
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001598
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001599 void printTag(const DINode *N);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001600 void printMacinfoType(const DIMacroNode *N);
Scott Linder71603842018-02-12 19:45:54 +00001601 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001602 void printString(StringRef Name, StringRef Value,
1603 bool ShouldSkipEmpty = true);
1604 void printMetadata(StringRef Name, const Metadata *MD,
1605 bool ShouldSkipNull = true);
1606 template <class IntTy>
1607 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
David Blaikiea01f2952016-08-24 18:29:49 +00001608 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001609 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001610 template <class IntTy, class Stringifier>
1611 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1612 bool ShouldSkipZero = true);
Adrian Prantlb939a252016-03-31 23:56:58 +00001613 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
David Blaikie66cf14d2018-08-16 21:29:55 +00001614 void printNameTableKind(StringRef Name,
1615 DICompileUnit::DebugNameTableKind NTK);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001616};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001617
1618} // end anonymous namespace
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001619
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001620void MDFieldPrinter::printTag(const DINode *N) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001621 Out << FS << "tag: ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001622 auto Tag = dwarf::TagString(N->getTag());
1623 if (!Tag.empty())
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001624 Out << Tag;
1625 else
1626 Out << N->getTag();
1627}
1628
Amjad Abouda9bcf162015-12-10 12:56:35 +00001629void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1630 Out << FS << "type: ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001631 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1632 if (!Type.empty())
Amjad Abouda9bcf162015-12-10 12:56:35 +00001633 Out << Type;
1634 else
1635 Out << N->getMacinfoType();
1636}
1637
Scott Linder71603842018-02-12 19:45:54 +00001638void MDFieldPrinter::printChecksum(
1639 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1640 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1641 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001642}
1643
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001644void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1645 bool ShouldSkipEmpty) {
1646 if (ShouldSkipEmpty && Value.empty())
1647 return;
1648
1649 Out << FS << Name << ": \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00001650 printEscapedString(Value, Out);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001651 Out << "\"";
1652}
1653
Duncan P. N. Exon Smith61a09332015-02-06 22:27:22 +00001654static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1655 TypePrinting *TypePrinter,
1656 SlotTracker *Machine,
1657 const Module *Context) {
1658 if (!MD) {
1659 Out << "null";
1660 return;
1661 }
1662 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1663}
1664
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001665void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1666 bool ShouldSkipNull) {
1667 if (ShouldSkipNull && !MD)
Duncan P. N. Exon Smith79cf9702015-02-28 22:16:56 +00001668 return;
1669
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001670 Out << FS << Name << ": ";
1671 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1672}
1673
1674template <class IntTy>
1675void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1676 if (ShouldSkipZero && !Int)
1677 return;
1678
1679 Out << FS << Name << ": " << Int;
1680}
1681
David Blaikiea01f2952016-08-24 18:29:49 +00001682void MDFieldPrinter::printBool(StringRef Name, bool Value,
1683 Optional<bool> Default) {
1684 if (Default && Value == *Default)
1685 return;
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001686 Out << FS << Name << ": " << (Value ? "true" : "false");
1687}
1688
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001689void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001690 if (!Flags)
1691 return;
1692
1693 Out << FS << Name << ": ";
1694
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001695 SmallVector<DINode::DIFlags, 8> SplitFlags;
1696 auto Extra = DINode::splitFlags(Flags, SplitFlags);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001697
1698 FieldSeparator FlagsFS(" | ");
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001699 for (auto F : SplitFlags) {
Mehdi Aminif42ec792016-10-01 05:57:50 +00001700 auto StringF = DINode::getFlagString(F);
1701 assert(!StringF.empty() && "Expected valid flag");
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001702 Out << FlagsFS << StringF;
1703 }
1704 if (Extra || SplitFlags.empty())
1705 Out << FlagsFS << Extra;
1706}
1707
Adrian Prantlb939a252016-03-31 23:56:58 +00001708void MDFieldPrinter::printEmissionKind(StringRef Name,
1709 DICompileUnit::DebugEmissionKind EK) {
Fangrui Song3c1b5db2018-07-06 19:26:00 +00001710 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
Adrian Prantlb939a252016-03-31 23:56:58 +00001711}
1712
David Blaikie66cf14d2018-08-16 21:29:55 +00001713void MDFieldPrinter::printNameTableKind(StringRef Name,
1714 DICompileUnit::DebugNameTableKind NTK) {
1715 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1716 return;
1717 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1718}
1719
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001720template <class IntTy, class Stringifier>
1721void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1722 Stringifier toString, bool ShouldSkipZero) {
1723 if (!Value)
1724 return;
1725
1726 Out << FS << Name << ": ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001727 auto S = toString(Value);
1728 if (!S.empty())
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001729 Out << S;
1730 else
1731 Out << Value;
Duncan P. N. Exon Smith79cf9702015-02-28 22:16:56 +00001732}
1733
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001734static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1735 TypePrinting *TypePrinter, SlotTracker *Machine,
1736 const Module *Context) {
1737 Out << "!GenericDINode(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001738 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1739 Printer.printTag(N);
1740 Printer.printString("header", N->getHeader());
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001741 if (N->getNumDwarfOperands()) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001742 Out << Printer.FS << "operands: {";
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001743 FieldSeparator IFS;
1744 for (auto &I : N->dwarf_operands()) {
1745 Out << IFS;
Duncan P. N. Exon Smith61a09332015-02-06 22:27:22 +00001746 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001747 }
1748 Out << "}";
1749 }
1750 Out << ")";
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +00001751}
1752
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001753static void writeDILocation(raw_ostream &Out, const DILocation *DL,
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001754 TypePrinting *TypePrinter, SlotTracker *Machine,
1755 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001756 Out << "!DILocation(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001757 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith503cf3b2015-01-14 22:14:26 +00001758 // Always output the line, since 0 is a relevant and important value for it.
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001759 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1760 Printer.printInt("column", DL->getColumn());
1761 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1762 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001763 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1764 /* Default */ false);
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001765 Out << ")";
1766}
1767
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001768static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
Sander de Smalenfdf40912018-01-24 09:56:07 +00001769 TypePrinting *TypePrinter, SlotTracker *Machine,
1770 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001771 Out << "!DISubrange(";
Sander de Smalenfdf40912018-01-24 09:56:07 +00001772 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1773 if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1774 Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1775 else
1776 Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
1777 /*ShouldSkipNull */ false);
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001778 Printer.printInt("lowerBound", N->getLowerBound());
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001779 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001780}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001781
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001782static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001783 TypePrinting *, SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001784 Out << "!DIEnumerator(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001785 MDFieldPrinter Printer(Out);
1786 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001787 if (N->isUnsigned()) {
1788 auto Value = static_cast<uint64_t>(N->getValue());
1789 Printer.printInt("value", Value, /* ShouldSkipZero */ false);
1790 Printer.printBool("isUnsigned", true);
1791 } else {
1792 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1793 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001794 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001795}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001796
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001797static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001798 TypePrinting *, SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001799 Out << "!DIBasicType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001800 MDFieldPrinter Printer(Out);
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00001801 if (N->getTag() != dwarf::DW_TAG_base_type)
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001802 Printer.printTag(N);
1803 Printer.printString("name", N->getName());
1804 Printer.printInt("size", N->getSizeInBits());
1805 Printer.printInt("align", N->getAlignInBits());
1806 Printer.printDwarfEnum("encoding", N->getEncoding(),
1807 dwarf::AttributeEncodingString);
Adrian Prantl55f42622018-08-14 19:35:34 +00001808 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001809 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001810}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001811
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001812static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001813 TypePrinting *TypePrinter, SlotTracker *Machine,
1814 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001815 Out << "!DIDerivedType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001816 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1817 Printer.printTag(N);
1818 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001819 Printer.printMetadata("scope", N->getRawScope());
1820 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001821 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001822 Printer.printMetadata("baseType", N->getRawBaseType(),
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001823 /* ShouldSkipNull */ false);
1824 Printer.printInt("size", N->getSizeInBits());
1825 Printer.printInt("align", N->getAlignInBits());
1826 Printer.printInt("offset", N->getOffsetInBits());
1827 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001828 Printer.printMetadata("extraData", N->getRawExtraData());
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001829 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1830 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1831 /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001832 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001833}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001834
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001835static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001836 TypePrinting *TypePrinter,
1837 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001838 Out << "!DICompositeType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001839 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1840 Printer.printTag(N);
1841 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001842 Printer.printMetadata("scope", N->getRawScope());
1843 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001844 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001845 Printer.printMetadata("baseType", N->getRawBaseType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001846 Printer.printInt("size", N->getSizeInBits());
1847 Printer.printInt("align", N->getAlignInBits());
1848 Printer.printInt("offset", N->getOffsetInBits());
1849 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001850 Printer.printMetadata("elements", N->getRawElements());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001851 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1852 dwarf::LanguageString);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001853 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1854 Printer.printMetadata("templateParams", N->getRawTemplateParams());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001855 Printer.printString("identifier", N->getIdentifier());
Adrian Prantl8c599212018-02-06 23:45:59 +00001856 Printer.printMetadata("discriminator", N->getRawDiscriminator());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001857 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001858}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001859
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001860static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001861 TypePrinting *TypePrinter,
1862 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001863 Out << "!DISubroutineType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001864 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1865 Printer.printDIFlags("flags", N->getFlags());
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001866 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001867 Printer.printMetadata("types", N->getRawTypeArray(),
1868 /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001869 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001870}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001871
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001872static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001873 SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001874 Out << "!DIFile(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001875 MDFieldPrinter Printer(Out);
1876 Printer.printString("filename", N->getFilename(),
1877 /* ShouldSkipEmpty */ false);
1878 Printer.printString("directory", N->getDirectory(),
1879 /* ShouldSkipEmpty */ false);
Scott Linder71603842018-02-12 19:45:54 +00001880 // Print all values for checksum together, or not at all.
1881 if (N->getChecksum())
1882 Printer.printChecksum(*N->getChecksum());
Scott Linder16c7bda2018-02-23 23:01:06 +00001883 Printer.printString("source", N->getSource().getValueOr(StringRef()),
1884 /* ShouldSkipEmpty */ true);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001885 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001886}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001887
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001888static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001889 TypePrinting *TypePrinter, SlotTracker *Machine,
1890 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001891 Out << "!DICompileUnit(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001892 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1893 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1894 dwarf::LanguageString, /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001895 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001896 Printer.printString("producer", N->getProducer());
1897 Printer.printBool("isOptimized", N->isOptimized());
1898 Printer.printString("flags", N->getFlags());
1899 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1900 /* ShouldSkipZero */ false);
1901 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
Adrian Prantlb939a252016-03-31 23:56:58 +00001902 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001903 Printer.printMetadata("enums", N->getRawEnumTypes());
1904 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001905 Printer.printMetadata("globals", N->getRawGlobalVariables());
1906 Printer.printMetadata("imports", N->getRawImportedEntities());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001907 Printer.printMetadata("macros", N->getRawMacros());
Adrian Prantl1f599f92015-05-21 20:37:30 +00001908 Printer.printInt("dwoId", N->getDWOId());
David Blaikiea01f2952016-08-24 18:29:49 +00001909 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
Dehao Chen0944a8c2017-02-01 22:45:09 +00001910 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1911 false);
David Blaikie66cf14d2018-08-16 21:29:55 +00001912 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001913 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001914}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001915
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001916static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001917 TypePrinting *TypePrinter, SlotTracker *Machine,
1918 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001919 Out << "!DISubprogram(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001920 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1921 Printer.printString("name", N->getName());
1922 Printer.printString("linkageName", N->getLinkageName());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001923 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1924 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001925 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001926 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001927 Printer.printBool("isLocal", N->isLocalToUnit());
1928 Printer.printBool("isDefinition", N->isDefinition());
1929 Printer.printInt("scopeLine", N->getScopeLine());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001930 Printer.printMetadata("containingType", N->getRawContainingType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001931 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1932 dwarf::VirtualityString);
Peter Collingbournea1f86252016-03-17 23:58:03 +00001933 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1934 N->getVirtualIndex() != 0)
1935 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001936 Printer.printInt("thisAdjustment", N->getThisAdjustment());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001937 Printer.printDIFlags("flags", N->getFlags());
1938 Printer.printBool("isOptimized", N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001939 Printer.printMetadata("unit", N->getRawUnit());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001940 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1941 Printer.printMetadata("declaration", N->getRawDeclaration());
Shiva Chen2c864552018-05-09 02:40:45 +00001942 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001943 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001944 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001945}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001946
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001947static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1948 TypePrinting *TypePrinter, SlotTracker *Machine,
1949 const Module *Context) {
1950 Out << "!DILexicalBlock(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001951 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001952 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1953 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001954 Printer.printInt("line", N->getLine());
1955 Printer.printInt("column", N->getColumn());
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001956 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001957}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001958
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001959static void writeDILexicalBlockFile(raw_ostream &Out,
1960 const DILexicalBlockFile *N,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001961 TypePrinting *TypePrinter,
1962 SlotTracker *Machine,
1963 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001964 Out << "!DILexicalBlockFile(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001965 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001966 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1967 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001968 Printer.printInt("discriminator", N->getDiscriminator(),
1969 /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001970 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001971}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001972
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001973static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001974 TypePrinting *TypePrinter, SlotTracker *Machine,
1975 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001976 Out << "!DINamespace(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001977 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1978 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001979 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Adrian Prantldbfda632016-11-03 19:42:02 +00001980 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001981 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001982}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001983
Amjad Abouda9bcf162015-12-10 12:56:35 +00001984static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1985 TypePrinting *TypePrinter, SlotTracker *Machine,
1986 const Module *Context) {
1987 Out << "!DIMacro(";
1988 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1989 Printer.printMacinfoType(N);
1990 Printer.printInt("line", N->getLine());
1991 Printer.printString("name", N->getName());
1992 Printer.printString("value", N->getValue());
1993 Out << ")";
1994}
1995
1996static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1997 TypePrinting *TypePrinter, SlotTracker *Machine,
1998 const Module *Context) {
1999 Out << "!DIMacroFile(";
2000 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2001 Printer.printInt("line", N->getLine());
2002 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2003 Printer.printMetadata("nodes", N->getRawElements());
2004 Out << ")";
2005}
2006
Adrian Prantlab1243f2015-06-29 23:03:47 +00002007static void writeDIModule(raw_ostream &Out, const DIModule *N,
2008 TypePrinting *TypePrinter, SlotTracker *Machine,
2009 const Module *Context) {
2010 Out << "!DIModule(";
2011 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2012 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2013 Printer.printString("name", N->getName());
2014 Printer.printString("configMacros", N->getConfigurationMacros());
2015 Printer.printString("includePath", N->getIncludePath());
2016 Printer.printString("isysroot", N->getISysRoot());
2017 Out << ")";
2018}
2019
2020
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002021static void writeDITemplateTypeParameter(raw_ostream &Out,
2022 const DITemplateTypeParameter *N,
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002023 TypePrinting *TypePrinter,
2024 SlotTracker *Machine,
2025 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002026 Out << "!DITemplateTypeParameter(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002027 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2028 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith3ec5fa62015-04-06 19:03:45 +00002029 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002030 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002031}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002032
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002033static void writeDITemplateValueParameter(raw_ostream &Out,
2034 const DITemplateValueParameter *N,
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002035 TypePrinting *TypePrinter,
2036 SlotTracker *Machine,
2037 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002038 Out << "!DITemplateValueParameter(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002039 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00002040 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002041 Printer.printTag(N);
2042 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith3ec5fa62015-04-06 19:03:45 +00002043 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002044 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002045 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002046}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002047
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002048static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002049 TypePrinting *TypePrinter,
2050 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002051 Out << "!DIGlobalVariable(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002052 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2053 Printer.printString("name", N->getName());
2054 Printer.printString("linkageName", N->getLinkageName());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002055 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2056 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002057 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002058 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002059 Printer.printBool("isLocal", N->isLocalToUnit());
2060 Printer.printBool("isDefinition", N->isDefinition());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002061 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
Victor Leschuk2ede1262016-10-20 00:13:12 +00002062 Printer.printInt("align", N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002063 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002064}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002065
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002066static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002067 TypePrinting *TypePrinter,
2068 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002069 Out << "!DILocalVariable(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002070 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002071 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002072 Printer.printInt("arg", N->getArg());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002073 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2074 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002075 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002076 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002077 Printer.printDIFlags("flags", N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00002078 Printer.printInt("align", N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002079 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002080}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002081
Shiva Chen2c864552018-05-09 02:40:45 +00002082static void writeDILabel(raw_ostream &Out, const DILabel *N,
2083 TypePrinting *TypePrinter,
2084 SlotTracker *Machine, const Module *Context) {
2085 Out << "!DILabel(";
2086 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2087 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2088 Printer.printString("name", N->getName());
2089 Printer.printMetadata("file", N->getRawFile());
2090 Printer.printInt("line", N->getLine());
2091 Out << ")";
2092}
2093
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002094static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002095 TypePrinting *TypePrinter, SlotTracker *Machine,
2096 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002097 Out << "!DIExpression(";
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002098 FieldSeparator FS;
2099 if (N->isValid()) {
2100 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
Mehdi Amini149f6ea2016-10-05 05:59:29 +00002101 auto OpStr = dwarf::OperationEncodingString(I->getOp());
2102 assert(!OpStr.empty() && "Expected valid opcode");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002103
2104 Out << FS << OpStr;
2105 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2106 Out << FS << I->getArg(A);
2107 }
2108 } else {
2109 for (const auto &I : N->getElements())
2110 Out << FS << I;
2111 }
2112 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002113}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002114
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002115static void writeDIGlobalVariableExpression(raw_ostream &Out,
2116 const DIGlobalVariableExpression *N,
2117 TypePrinting *TypePrinter,
2118 SlotTracker *Machine,
2119 const Module *Context) {
2120 Out << "!DIGlobalVariableExpression(";
2121 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2122 Printer.printMetadata("var", N->getVariable());
2123 Printer.printMetadata("expr", N->getExpression());
2124 Out << ")";
2125}
2126
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002127static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002128 TypePrinting *TypePrinter, SlotTracker *Machine,
2129 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002130 Out << "!DIObjCProperty(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002131 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2132 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002133 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002134 Printer.printInt("line", N->getLine());
2135 Printer.printString("setter", N->getSetterName());
2136 Printer.printString("getter", N->getGetterName());
2137 Printer.printInt("attributes", N->getAttributes());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002138 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002139 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002140}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002141
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002142static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002143 TypePrinting *TypePrinter,
2144 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002145 Out << "!DIImportedEntity(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002146 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2147 Printer.printTag(N);
2148 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002149 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2150 Printer.printMetadata("entity", N->getRawEntity());
Adrian Prantld63bfd22017-07-19 00:09:54 +00002151 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002152 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002153 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002154}
2155
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002156static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2157 TypePrinting *TypePrinter,
2158 SlotTracker *Machine,
2159 const Module *Context) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002160 if (Node->isDistinct())
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002161 Out << "distinct ";
Duncan P. N. Exon Smith3d510662015-03-16 21:21:10 +00002162 else if (Node->isTemporary())
2163 Out << "<temporary!> "; // Handle broken code.
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002164
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002165 switch (Node->getMetadataID()) {
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002166 default:
2167 llvm_unreachable("Expected uniquable MDNode");
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002168#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002169 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002170 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002171 break;
2172#include "llvm/IR/Metadata.def"
2173 }
2174}
2175
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002176// Full implementation of printing a Value as an operand with support for
2177// TypePrinting, etc.
Dan Gohman12dad632009-08-12 20:56:03 +00002178static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
Dan Gohman8061d9e2009-08-13 15:27:57 +00002179 TypePrinting *TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00002180 SlotTracker *Machine,
2181 const Module *Context) {
Chris Lattner033935d2008-08-17 04:40:13 +00002182 if (V->hasName()) {
2183 PrintLLVMName(Out, V);
2184 return;
2185 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattner033935d2008-08-17 04:40:13 +00002187 const Constant *CV = dyn_cast<Constant>(V);
2188 if (CV && !isa<GlobalValue>(CV)) {
Dan Gohman8061d9e2009-08-13 15:27:57 +00002189 assert(TypePrinter && "Constants require TypePrinting!");
Dan Gohmana2489d12010-07-20 23:55:01 +00002190 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002191 return;
2192 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002194 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Chris Lattner033935d2008-08-17 04:40:13 +00002195 Out << "asm ";
2196 if (IA->hasSideEffects())
2197 Out << "sideeffect ";
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002198 if (IA->isAlignStack())
2199 Out << "alignstack ";
Chad Rosierd8c76102012-09-05 19:00:49 +00002200 // We don't emit the AD_ATT dialect as it's the assumed default.
2201 if (IA->getDialect() == InlineAsm::AD_Intel)
2202 Out << "inteldialect ";
Chris Lattner033935d2008-08-17 04:40:13 +00002203 Out << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002204 printEscapedString(IA->getAsmString(), Out);
Chris Lattner033935d2008-08-17 04:40:13 +00002205 Out << "\", \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002206 printEscapedString(IA->getConstraintString(), Out);
Chris Lattner033935d2008-08-17 04:40:13 +00002207 Out << '"';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002208 return;
2209 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002210
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002211 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2212 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2213 Context, /* FromValue */ true);
Devang Patel7428d8a2009-07-22 17:43:22 +00002214 return;
2215 }
2216
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002217 char Prefix = '%';
2218 int Slot;
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002219 // If we have a SlotTracker, use it.
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002220 if (Machine) {
2221 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2222 Slot = Machine->getGlobalSlot(GV);
2223 Prefix = '@';
2224 } else {
2225 Slot = Machine->getLocalSlot(V);
Andrew Trickec4b6e72011-09-30 19:48:58 +00002226
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002227 // If the local value didn't succeed, then we may be referring to a value
2228 // from a different function. Translate it, as this can happen when using
2229 // address of blocks.
2230 if (Slot == -1)
2231 if ((Machine = createSlotTracker(V))) {
2232 Slot = Machine->getLocalSlot(V);
2233 delete Machine;
2234 }
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002235 }
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002236 } else if ((Machine = createSlotTracker(V))) {
2237 // Otherwise, create one to get the # and then destroy it.
2238 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2239 Slot = Machine->getGlobalSlot(GV);
2240 Prefix = '@';
Chris Lattnera2d810d2006-01-25 22:26:05 +00002241 } else {
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002242 Slot = Machine->getLocalSlot(V);
Chris Lattnerd84bb632002-04-16 21:36:08 +00002243 }
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002244 delete Machine;
Craig Topperc6207612014-04-09 06:08:46 +00002245 Machine = nullptr;
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002246 } else {
2247 Slot = -1;
Chris Lattnerd84bb632002-04-16 21:36:08 +00002248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002250 if (Slot != -1)
2251 Out << Prefix << Slot;
2252 else
2253 Out << "<badref>";
Chris Lattnerd84bb632002-04-16 21:36:08 +00002254}
2255
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002256static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2257 TypePrinting *TypePrinter,
2258 SlotTracker *Machine, const Module *Context,
2259 bool FromValue) {
Reid Kleckner6d353342017-08-23 20:31:27 +00002260 // Write DIExpressions inline when used as a value. Improves readability of
2261 // debug info intrinsics.
2262 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2263 writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2264 return;
2265 }
2266
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002267 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smithf8b3ad62015-06-27 00:15:32 +00002268 std::unique_ptr<SlotTracker> MachineStorage;
2269 if (!Machine) {
2270 MachineStorage = make_unique<SlotTracker>(Context);
2271 Machine = MachineStorage.get();
2272 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002273 int Slot = Machine->getMetadataSlot(N);
2274 if (Slot == -1)
Duncan P. N. Exon Smithfee167f2014-12-16 07:09:37 +00002275 // Give the pointer value instead of "badref", since this comes up all
2276 // the time when debugging.
2277 Out << "<" << N << ">";
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002278 else
2279 Out << '!' << Slot;
2280 return;
2281 }
2282
2283 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2284 Out << "!\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002285 printEscapedString(MDS->getString(), Out);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002286 Out << '"';
2287 return;
2288 }
2289
2290 auto *V = cast<ValueAsMetadata>(MD);
2291 assert(TypePrinter && "TypePrinter required for metadata values");
2292 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2293 "Unexpected function-local metadata outside of value argument");
2294
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002295 TypePrinter->print(V->getValue()->getType(), Out);
2296 Out << ' ';
2297 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002298}
2299
Benjamin Kramerba05a782015-03-17 19:53:41 +00002300namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00002301
Benjamin Kramerba05a782015-03-17 19:53:41 +00002302class AssemblyWriter {
2303 formatted_raw_ostream &Out;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002304 const Module *TheModule = nullptr;
2305 const ModuleSummaryIndex *TheIndex = nullptr;
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00002306 std::unique_ptr<SlotTracker> SlotTrackerStorage;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002307 SlotTracker &Machine;
2308 TypePrinting TypePrinter;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002309 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002310 SetVector<const Comdat *> Comdats;
Justin Bognerd7d1a722015-09-27 22:38:50 +00002311 bool IsForDebug;
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002312 bool ShouldPreserveUseListOrder;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002313 UseListOrderStack UseListOrders;
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00002314 SmallVector<StringRef, 8> MDNames;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002315 /// Synchronization scope names registered with LLVMContext.
2316 SmallVector<StringRef, 8> SSNs;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002317 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002318
2319public:
2320 /// Construct an AssemblyWriter with an external SlotTracker
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002321 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
Justin Bognerd7d1a722015-09-27 22:38:50 +00002322 AssemblyAnnotationWriter *AAW, bool IsForDebug,
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002323 bool ShouldPreserveUseListOrder = false);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002324
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002325 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2326 const ModuleSummaryIndex *Index, bool IsForDebug);
2327
Benjamin Kramerba05a782015-03-17 19:53:41 +00002328 void printMDNodeBody(const MDNode *MD);
2329 void printNamedMDNode(const NamedMDNode *NMD);
2330
2331 void printModule(const Module *M);
2332
2333 void writeOperand(const Value *Op, bool PrintType);
Reid Kleckner6652a522017-04-28 18:37:16 +00002334 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002335 void writeOperandBundles(ImmutableCallSite CS);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002336 void writeSyncScope(const LLVMContext &Context,
2337 SyncScope::ID SSID);
2338 void writeAtomic(const LLVMContext &Context,
2339 AtomicOrdering Ordering,
2340 SyncScope::ID SSID);
2341 void writeAtomicCmpXchg(const LLVMContext &Context,
2342 AtomicOrdering SuccessOrdering,
Benjamin Kramerba05a782015-03-17 19:53:41 +00002343 AtomicOrdering FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002344 SyncScope::ID SSID);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002345
2346 void writeAllMDNodes();
2347 void writeMDNode(unsigned Slot, const MDNode *Node);
2348 void writeAllAttributeGroups();
2349
2350 void printTypeIdentities();
2351 void printGlobal(const GlobalVariable *GV);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002352 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002353 void printComdat(const Comdat *C);
2354 void printFunction(const Function *F);
Reid Kleckner6652a522017-04-28 18:37:16 +00002355 void printArgument(const Argument *FA, AttributeSet Attrs);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002356 void printBasicBlock(const BasicBlock *BB);
2357 void printInstructionLine(const Instruction &I);
2358 void printInstruction(const Instruction &I);
2359
2360 void printUseListOrder(const UseListOrder &Order);
2361 void printUseLists(const Function *F);
2362
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002363 void printModuleSummaryIndex();
2364 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2365 void printSummary(const GlobalValueSummary &Summary);
2366 void printAliasSummary(const AliasSummary *AS);
2367 void printGlobalVarSummary(const GlobalVarSummary *GS);
2368 void printFunctionSummary(const FunctionSummary *FS);
2369 void printTypeIdSummary(const TypeIdSummary &TIS);
2370 void printTypeTestResolution(const TypeTestResolution &TTRes);
2371 void printArgs(const std::vector<uint64_t> &Args);
2372 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2373 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2374 void printVFuncId(const FunctionSummary::VFuncId VFId);
2375 void
2376 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2377 const char *Tag);
2378 void
2379 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2380 const char *Tag);
2381
Benjamin Kramerba05a782015-03-17 19:53:41 +00002382private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002383 /// Print out metadata attachments.
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00002384 void printMetadataAttachments(
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00002385 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2386 StringRef Separator);
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00002387
Benjamin Kramerba05a782015-03-17 19:53:41 +00002388 // printInfoComment - Print a little comment after the instruction indicating
2389 // which slot it occupies.
2390 void printInfoComment(const Value &V);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00002391
2392 // printGCRelocateComment - print comment after call to the gc.relocate
2393 // intrinsic indicating base and derived pointer names.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002394 void printGCRelocateComment(const GCRelocateInst &Relocate);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002395};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00002396
2397} // end anonymous namespace
Benjamin Kramerba05a782015-03-17 19:53:41 +00002398
Justin Bogner0ffea9d2015-09-02 22:46:15 +00002399AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2400 const Module *M, AssemblyAnnotationWriter *AAW,
Justin Bognerd7d1a722015-09-27 22:38:50 +00002401 bool IsForDebug, bool ShouldPreserveUseListOrder)
Roman Tereshind96de6f2018-03-22 21:29:07 +00002402 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
Justin Bognerd7d1a722015-09-27 22:38:50 +00002403 IsForDebug(IsForDebug),
Justin Bogner0ffea9d2015-09-02 22:46:15 +00002404 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
David Majnemerdad0a642014-06-27 18:19:56 +00002405 if (!TheModule)
2406 return;
Peter Collingbourne6d88fde2016-06-22 20:29:42 +00002407 for (const GlobalObject &GO : TheModule->global_objects())
2408 if (const Comdat *C = GO.getComdat())
David Majnemerdad0a642014-06-27 18:19:56 +00002409 Comdats.insert(C);
Daniel Maleaded9f932013-05-08 20:38:31 +00002410}
Chris Lattner2e9fee42001-07-12 23:35:26 +00002411
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002412AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2413 const ModuleSummaryIndex *Index, bool IsForDebug)
2414 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2415 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2416
Chris Lattner78e2e8b2006-12-06 06:24:27 +00002417void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
Craig Topperc6207612014-04-09 06:08:46 +00002418 if (!Operand) {
Chris Lattner08f7d0c2005-02-24 16:58:29 +00002419 Out << "<null operand!>";
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002420 return;
Chris Lattner08f7d0c2005-02-24 16:58:29 +00002421 }
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002422 if (PrintType) {
2423 TypePrinter.print(Operand->getType(), Out);
2424 Out << ' ';
2425 }
Dan Gohmana2489d12010-07-20 23:55:01 +00002426 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
Chris Lattner2f7c9632001-06-06 20:29:01 +00002427}
2428
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002429void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2430 SyncScope::ID SSID) {
2431 switch (SSID) {
2432 case SyncScope::System: {
2433 break;
2434 }
2435 default: {
2436 if (SSNs.empty())
2437 Context.getSyncScopeNames(SSNs);
2438
2439 Out << " syncscope(\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002440 printEscapedString(SSNs[SSID], Out);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002441 Out << "\")";
2442 break;
2443 }
2444 }
2445}
2446
2447void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2448 AtomicOrdering Ordering,
2449 SyncScope::ID SSID) {
JF Bastien800f87a2016-04-06 21:19:33 +00002450 if (Ordering == AtomicOrdering::NotAtomic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00002451 return;
2452
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002453 writeSyncScope(Context, SSID);
JF Bastien800f87a2016-04-06 21:19:33 +00002454 Out << " " << toIRString(Ordering);
Eli Friedmanfee02c62011-07-25 23:16:38 +00002455}
2456
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002457void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2458 AtomicOrdering SuccessOrdering,
Tim Northovere94a5182014-03-11 10:48:52 +00002459 AtomicOrdering FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002460 SyncScope::ID SSID) {
JF Bastien800f87a2016-04-06 21:19:33 +00002461 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2462 FailureOrdering != AtomicOrdering::NotAtomic);
Tim Northovere94a5182014-03-11 10:48:52 +00002463
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002464 writeSyncScope(Context, SSID);
JF Bastien800f87a2016-04-06 21:19:33 +00002465 Out << " " << toIRString(SuccessOrdering);
2466 Out << " " << toIRString(FailureOrdering);
Tim Northovere94a5182014-03-11 10:48:52 +00002467}
2468
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002469void AssemblyWriter::writeParamOperand(const Value *Operand,
Reid Kleckner6652a522017-04-28 18:37:16 +00002470 AttributeSet Attrs) {
Craig Topperc6207612014-04-09 06:08:46 +00002471 if (!Operand) {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002472 Out << "<null operand!>";
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002473 return;
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002474 }
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002475
2476 // Print the type
2477 TypePrinter.print(Operand->getType(), Out);
2478 // Print parameter attributes list
Reid Kleckner6652a522017-04-28 18:37:16 +00002479 if (Attrs.hasAttributes())
2480 Out << ' ' << Attrs.getAsString();
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002481 Out << ' ';
2482 // Print the operand
Dan Gohmana2489d12010-07-20 23:55:01 +00002483 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002484}
Chris Lattner2f7c9632001-06-06 20:29:01 +00002485
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002486void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2487 if (!CS.hasOperandBundles())
2488 return;
2489
2490 Out << " [ ";
2491
2492 bool FirstBundle = true;
2493 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002494 OperandBundleUse BU = CS.getOperandBundleAt(i);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002495
2496 if (!FirstBundle)
2497 Out << ", ";
2498 FirstBundle = false;
2499
2500 Out << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002501 printEscapedString(BU.getTagName(), Out);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002502 Out << '"';
2503
2504 Out << '(';
2505
2506 bool FirstInput = true;
2507 for (const auto &Input : BU.Inputs) {
2508 if (!FirstInput)
2509 Out << ", ";
2510 FirstInput = false;
2511
2512 TypePrinter.print(Input->getType(), Out);
2513 Out << " ";
2514 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2515 }
2516
2517 Out << ')';
2518 }
2519
2520 Out << " ]";
2521}
2522
Chris Lattner7bfee412001-10-29 16:05:51 +00002523void AssemblyWriter::printModule(const Module *M) {
Teresa Johnsonfc801f52018-07-03 15:52:57 +00002524 Machine.initializeIfNeeded();
Bill Wendling829b4782013-02-11 08:43:33 +00002525
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002526 if (ShouldPreserveUseListOrder)
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002527 UseListOrders = predictUseListOrder(M);
2528
Chris Lattner4d8689e2005-03-02 23:12:40 +00002529 if (!M->getModuleIdentifier().empty() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00002530 // Don't print the ID if it will start a new line (which would
Chris Lattner4d8689e2005-03-02 23:12:40 +00002531 // require a comment char before it).
2532 M->getModuleIdentifier().find('\n') == std::string::npos)
2533 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2534
Teresa Johnson83c517c2016-03-30 18:15:08 +00002535 if (!M->getSourceFileName().empty()) {
Teresa Johnsond8d94652016-03-30 22:17:28 +00002536 Out << "source_filename = \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002537 printEscapedString(M->getSourceFileName(), Out);
Teresa Johnsond8d94652016-03-30 22:17:28 +00002538 Out << "\"\n";
Teresa Johnson83c517c2016-03-30 18:15:08 +00002539 }
2540
Rafael Espindolaf863ee22014-02-25 20:01:08 +00002541 const std::string &DL = M->getDataLayoutStr();
2542 if (!DL.empty())
2543 Out << "target datalayout = \"" << DL << "\"\n";
Reid Spencer48f98c82004-07-25 21:44:54 +00002544 if (!M->getTargetTriple().empty())
Reid Spencerffec7df2004-07-25 21:29:43 +00002545 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00002546
Chris Lattnereef2fe72006-01-24 04:13:11 +00002547 if (!M->getModuleInlineAsm().empty()) {
Dan Gohman69273e62009-08-12 23:54:22 +00002548 Out << '\n';
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002549
2550 // Split the string into lines, to make it easier to read the .ll file.
Benjamin Kramerf1cfc422015-06-08 18:58:57 +00002551 StringRef Asm = M->getModuleInlineAsm();
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002552 do {
2553 StringRef Front;
2554 std::tie(Front, Asm) = Asm.split('\n');
2555
Chris Lattnerefaf35d2006-01-24 00:45:30 +00002556 // We found a newline, print the portion of the asm string from the
2557 // last newline up to this newline.
2558 Out << "module asm \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002559 printEscapedString(Front, Out);
Chris Lattnerefaf35d2006-01-24 00:45:30 +00002560 Out << "\"\n";
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002561 } while (!Asm.empty());
Chris Lattner6ed87bd2006-01-23 23:03:36 +00002562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002564 printTypeIdentities();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002565
David Majnemerdad0a642014-06-27 18:19:56 +00002566 // Output all comdats.
2567 if (!Comdats.empty())
2568 Out << '\n';
2569 for (const Comdat *C : Comdats) {
2570 printComdat(C);
2571 if (C != Comdats.back())
2572 Out << '\n';
2573 }
2574
Dan Gohman69273e62009-08-12 23:54:22 +00002575 // Output all globals.
2576 if (!M->global_empty()) Out << '\n';
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002577 for (const GlobalVariable &GV : M->globals()) {
2578 printGlobal(&GV); Out << '\n';
Duncan Sands66fc0e62012-09-12 09:55:51 +00002579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002580
Chris Lattnerd2747052007-04-26 02:24:10 +00002581 // Output all aliases.
2582 if (!M->alias_empty()) Out << "\n";
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002583 for (const GlobalAlias &GA : M->aliases())
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002584 printIndirectSymbol(&GA);
Chris Lattnerfee714f2001-09-07 16:36:04 +00002585
Dmitry Polukhina1feff72016-04-07 12:32:19 +00002586 // Output all ifuncs.
2587 if (!M->ifunc_empty()) Out << "\n";
2588 for (const GlobalIFunc &GI : M->ifuncs())
2589 printIndirectSymbol(&GI);
2590
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002591 // Output global use-lists.
2592 printUseLists(nullptr);
2593
Chris Lattner2cdd49d2004-09-14 05:06:58 +00002594 // Output all of the functions.
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002595 for (const Function &F : *M)
2596 printFunction(&F);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002597 assert(UseListOrders.empty() && "All use-lists should have been consumed");
Devang Patel983c6b12009-07-08 21:44:25 +00002598
Bill Wendling829b4782013-02-11 08:43:33 +00002599 // Output all attribute groups.
Bill Wendling04945972013-04-29 23:48:06 +00002600 if (!Machine.as_empty()) {
Bill Wendling829b4782013-02-11 08:43:33 +00002601 Out << '\n';
2602 writeAllAttributeGroups();
2603 }
2604
Devang Patel23e68302009-07-29 22:04:47 +00002605 // Output named metadata.
Dan Gohman69273e62009-08-12 23:54:22 +00002606 if (!M->named_metadata_empty()) Out << '\n';
Andrew Trickec4b6e72011-09-30 19:48:58 +00002607
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002608 for (const NamedMDNode &Node : M->named_metadata())
2609 printNamedMDNode(&Node);
Devang Patel23e68302009-07-29 22:04:47 +00002610
2611 // Output metadata.
Chris Lattnercf4a76e2009-12-31 02:20:11 +00002612 if (!Machine.mdn_empty()) {
Chris Lattnerbddea6a2009-12-31 02:13:35 +00002613 Out << '\n';
2614 writeAllMDNodes();
2615 }
Chris Lattnerfee714f2001-09-07 16:36:04 +00002616}
2617
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002618void AssemblyWriter::printModuleSummaryIndex() {
2619 assert(TheIndex);
Teresa Johnsonfc801f52018-07-03 15:52:57 +00002620 Machine.initializeIndexIfNeeded();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002621
2622 Out << "\n";
2623
Teresa Johnson8fc76662018-07-02 22:09:23 +00002624 // Print module path entries. To print in order, add paths to a vector
2625 // indexed by module slot.
Teresa Johnson724e7a12018-05-26 02:53:52 +00002626 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002627 std::string RegularLTOModuleName = "[Regular LTO]";
2628 moduleVec.resize(TheIndex->modulePaths().size());
Teresa Johnson8fc76662018-07-02 22:09:23 +00002629 for (auto &ModPath : TheIndex->modulePaths())
2630 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2631 // A module id of -1 is a special entry for a regular LTO module created
2632 // during the thin link.
2633 ModPath.second.first == -1u ? RegularLTOModuleName
2634 : (std::string)ModPath.first(),
2635 ModPath.second.second);
2636
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002637 unsigned i = 0;
2638 for (auto &ModPair : moduleVec) {
2639 Out << "^" << i++ << " = module: (";
Andrew Ngac305e12018-07-12 14:40:21 +00002640 Out << "path: \"";
2641 printEscapedString(ModPair.first, Out);
2642 Out << "\", hash: (";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002643 FieldSeparator FS;
2644 for (auto Hash : ModPair.second)
2645 Out << FS << Hash;
2646 Out << "))\n";
2647 }
2648
2649 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2650 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2651 for (auto &GlobalList : *TheIndex) {
2652 auto GUID = GlobalList.first;
2653 for (auto &Summary : GlobalList.second.SummaryList)
2654 SummaryToGUIDMap[Summary.get()] = GUID;
2655 }
2656
2657 // Print the global value summary entries.
2658 for (auto &GlobalList : *TheIndex) {
2659 auto GUID = GlobalList.first;
2660 auto VI = TheIndex->getValueInfo(GlobalList);
2661 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2662 }
2663
2664 // Print the TypeIdMap entries.
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002665 for (auto TidIter = TheIndex->typeIds().begin();
2666 TidIter != TheIndex->typeIds().end(); TidIter++) {
2667 Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2668 << " = typeid: (name: \"" << TidIter->second.first << "\"";
2669 printTypeIdSummary(TidIter->second.second);
2670 Out << ") ; guid = " << TidIter->first << "\n";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002671 }
2672}
2673
2674static const char *
2675getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2676 switch (K) {
2677 case WholeProgramDevirtResolution::Indir:
2678 return "indir";
2679 case WholeProgramDevirtResolution::SingleImpl:
2680 return "singleImpl";
2681 case WholeProgramDevirtResolution::BranchFunnel:
2682 return "branchFunnel";
2683 }
2684 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2685}
2686
2687static const char *getWholeProgDevirtResByArgKindName(
2688 WholeProgramDevirtResolution::ByArg::Kind K) {
2689 switch (K) {
2690 case WholeProgramDevirtResolution::ByArg::Indir:
2691 return "indir";
2692 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2693 return "uniformRetVal";
2694 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2695 return "uniqueRetVal";
2696 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2697 return "virtualConstProp";
2698 }
2699 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2700}
2701
2702static const char *getTTResKindName(TypeTestResolution::Kind K) {
2703 switch (K) {
2704 case TypeTestResolution::Unsat:
2705 return "unsat";
2706 case TypeTestResolution::ByteArray:
2707 return "byteArray";
2708 case TypeTestResolution::Inline:
2709 return "inline";
2710 case TypeTestResolution::Single:
2711 return "single";
2712 case TypeTestResolution::AllOnes:
2713 return "allOnes";
2714 }
2715 llvm_unreachable("invalid TypeTestResolution kind");
2716}
2717
2718void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2719 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2720 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2721
2722 // The following fields are only used if the target does not support the use
2723 // of absolute symbols to store constants. Print only if non-zero.
2724 if (TTRes.AlignLog2)
2725 Out << ", alignLog2: " << TTRes.AlignLog2;
2726 if (TTRes.SizeM1)
2727 Out << ", sizeM1: " << TTRes.SizeM1;
2728 if (TTRes.BitMask)
2729 // BitMask is uint8_t which causes it to print the corresponding char.
2730 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2731 if (TTRes.InlineBits)
2732 Out << ", inlineBits: " << TTRes.InlineBits;
2733
2734 Out << ")";
2735}
2736
2737void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2738 Out << ", summary: (";
2739 printTypeTestResolution(TIS.TTRes);
2740 if (!TIS.WPDRes.empty()) {
2741 Out << ", wpdResolutions: (";
2742 FieldSeparator FS;
2743 for (auto &WPDRes : TIS.WPDRes) {
2744 Out << FS;
2745 Out << "(offset: " << WPDRes.first << ", ";
2746 printWPDRes(WPDRes.second);
2747 Out << ")";
2748 }
2749 Out << ")";
2750 }
2751 Out << ")";
2752}
2753
2754void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2755 Out << "args: (";
2756 FieldSeparator FS;
2757 for (auto arg : Args) {
2758 Out << FS;
2759 Out << arg;
2760 }
2761 Out << ")";
2762}
2763
2764void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2765 Out << "wpdRes: (kind: ";
2766 Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2767
2768 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2769 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2770
2771 if (!WPDRes.ResByArg.empty()) {
2772 Out << ", resByArg: (";
2773 FieldSeparator FS;
2774 for (auto &ResByArg : WPDRes.ResByArg) {
2775 Out << FS;
2776 printArgs(ResByArg.first);
2777 Out << ", byArg: (kind: ";
2778 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2779 if (ResByArg.second.TheKind ==
2780 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2781 ResByArg.second.TheKind ==
2782 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2783 Out << ", info: " << ResByArg.second.Info;
2784
2785 // The following fields are only used if the target does not support the
2786 // use of absolute symbols to store constants. Print only if non-zero.
2787 if (ResByArg.second.Byte || ResByArg.second.Bit)
2788 Out << ", byte: " << ResByArg.second.Byte
2789 << ", bit: " << ResByArg.second.Bit;
2790
2791 Out << ")";
2792 }
2793 Out << ")";
2794 }
2795 Out << ")";
2796}
2797
2798static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2799 switch (SK) {
2800 case GlobalValueSummary::AliasKind:
2801 return "alias";
2802 case GlobalValueSummary::FunctionKind:
2803 return "function";
2804 case GlobalValueSummary::GlobalVarKind:
2805 return "variable";
2806 }
2807 llvm_unreachable("invalid summary kind");
2808}
2809
2810void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
Teresa Johnsonf8182f12018-07-03 01:11:43 +00002811 Out << ", aliasee: ";
2812 // The indexes emitted for distributed backends may not include the
2813 // aliasee summary (only if it is being imported directly). Handle
2814 // that case by just emitting "null" as the aliasee.
2815 if (AS->hasAliasee())
2816 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2817 else
2818 Out << "null";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002819}
2820
2821void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2822 // Nothing for now
2823}
2824
Teresa Johnsonc80c8732018-05-25 15:15:39 +00002825static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2826 switch (LT) {
2827 case GlobalValue::ExternalLinkage:
2828 return "external";
2829 case GlobalValue::PrivateLinkage:
2830 return "private";
2831 case GlobalValue::InternalLinkage:
2832 return "internal";
2833 case GlobalValue::LinkOnceAnyLinkage:
2834 return "linkonce";
2835 case GlobalValue::LinkOnceODRLinkage:
2836 return "linkonce_odr";
2837 case GlobalValue::WeakAnyLinkage:
2838 return "weak";
2839 case GlobalValue::WeakODRLinkage:
2840 return "weak_odr";
2841 case GlobalValue::CommonLinkage:
2842 return "common";
2843 case GlobalValue::AppendingLinkage:
2844 return "appending";
2845 case GlobalValue::ExternalWeakLinkage:
2846 return "extern_weak";
2847 case GlobalValue::AvailableExternallyLinkage:
2848 return "available_externally";
2849 }
2850 llvm_unreachable("invalid linkage");
2851}
2852
2853// When printing the linkage types in IR where the ExternalLinkage is
2854// not printed, and other linkage types are expected to be printed with
2855// a space after the name.
2856static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2857 if (LT == GlobalValue::ExternalLinkage)
2858 return "";
2859 return getLinkageName(LT) + " ";
2860}
2861
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002862void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2863 Out << ", insts: " << FS->instCount();
2864
2865 FunctionSummary::FFlags FFlags = FS->fflags();
2866 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2867 FFlags.ReturnDoesNotAlias) {
2868 Out << ", funcFlags: (";
2869 Out << "readNone: " << FFlags.ReadNone;
2870 Out << ", readOnly: " << FFlags.ReadOnly;
2871 Out << ", noRecurse: " << FFlags.NoRecurse;
2872 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2873 Out << ")";
2874 }
2875 if (!FS->calls().empty()) {
2876 Out << ", calls: (";
2877 FieldSeparator IFS;
2878 for (auto &Call : FS->calls()) {
2879 Out << IFS;
2880 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2881 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2882 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2883 else if (Call.second.RelBlockFreq)
2884 Out << ", relbf: " << Call.second.RelBlockFreq;
2885 Out << ")";
2886 }
2887 Out << ")";
2888 }
2889
2890 if (const auto *TIdInfo = FS->getTypeIdInfo())
2891 printTypeIdInfo(*TIdInfo);
2892}
2893
2894void AssemblyWriter::printTypeIdInfo(
2895 const FunctionSummary::TypeIdInfo &TIDInfo) {
2896 Out << ", typeIdInfo: (";
2897 FieldSeparator TIDFS;
2898 if (!TIDInfo.TypeTests.empty()) {
2899 Out << TIDFS;
2900 Out << "typeTests: (";
2901 FieldSeparator FS;
2902 for (auto &GUID : TIDInfo.TypeTests) {
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002903 auto TidIter = TheIndex->typeIds().equal_range(GUID);
2904 if (TidIter.first == TidIter.second) {
2905 Out << FS;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002906 Out << GUID;
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002907 continue;
2908 }
2909 // Print all type id that correspond to this GUID.
2910 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2911 Out << FS;
2912 auto Slot = Machine.getTypeIdSlot(It->second.first);
2913 assert(Slot != -1);
2914 Out << "^" << Slot;
2915 }
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002916 }
2917 Out << ")";
2918 }
2919 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2920 Out << TIDFS;
2921 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2922 }
2923 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2924 Out << TIDFS;
2925 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2926 }
2927 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2928 Out << TIDFS;
2929 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2930 "typeTestAssumeConstVCalls");
2931 }
2932 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2933 Out << TIDFS;
2934 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2935 "typeCheckedLoadConstVCalls");
2936 }
2937 Out << ")";
2938}
2939
2940void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002941 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
2942 if (TidIter.first == TidIter.second) {
2943 Out << "vFuncId: (";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002944 Out << "guid: " << VFId.GUID;
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002945 Out << ", offset: " << VFId.Offset;
2946 Out << ")";
2947 return;
2948 }
2949 // Print all type id that correspond to this GUID.
2950 FieldSeparator FS;
2951 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2952 Out << FS;
2953 Out << "vFuncId: (";
2954 auto Slot = Machine.getTypeIdSlot(It->second.first);
2955 assert(Slot != -1);
2956 Out << "^" << Slot;
2957 Out << ", offset: " << VFId.Offset;
2958 Out << ")";
2959 }
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002960}
2961
2962void AssemblyWriter::printNonConstVCalls(
2963 const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
2964 Out << Tag << ": (";
2965 FieldSeparator FS;
2966 for (auto &VFuncId : VCallList) {
2967 Out << FS;
2968 printVFuncId(VFuncId);
2969 }
2970 Out << ")";
2971}
2972
2973void AssemblyWriter::printConstVCalls(
2974 const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
2975 Out << Tag << ": (";
2976 FieldSeparator FS;
2977 for (auto &ConstVCall : VCallList) {
2978 Out << FS;
Teresa Johnsonc7816802018-08-14 01:49:33 +00002979 Out << "(";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002980 printVFuncId(ConstVCall.VFunc);
2981 if (!ConstVCall.Args.empty()) {
2982 Out << ", ";
2983 printArgs(ConstVCall.Args);
2984 }
Teresa Johnsonc7816802018-08-14 01:49:33 +00002985 Out << ")";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002986 }
2987 Out << ")";
2988}
2989
2990void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
2991 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
2992 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
2993 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
Teresa Johnson8fc76662018-07-02 22:09:23 +00002994 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002995 << ", flags: (";
2996 Out << "linkage: " << getLinkageName(LT);
2997 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
2998 Out << ", live: " << GVFlags.Live;
2999 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3000 Out << ")";
3001
3002 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3003 printAliasSummary(cast<AliasSummary>(&Summary));
3004 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3005 printFunctionSummary(cast<FunctionSummary>(&Summary));
3006 else
3007 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3008
3009 auto RefList = Summary.refs();
3010 if (!RefList.empty()) {
3011 Out << ", refs: (";
3012 FieldSeparator FS;
3013 for (auto &Ref : RefList) {
3014 Out << FS;
3015 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3016 }
3017 Out << ")";
3018 }
3019
3020 Out << ")";
3021}
3022
3023void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3024 Out << "^" << Slot << " = gv: (";
3025 if (!VI.name().empty())
3026 Out << "name: \"" << VI.name() << "\"";
3027 else
3028 Out << "guid: " << VI.getGUID();
3029 if (!VI.getSummaryList().empty()) {
3030 Out << ", summaries: (";
3031 FieldSeparator FS;
3032 for (auto &Summary : VI.getSummaryList()) {
3033 Out << FS;
3034 printSummary(*Summary);
3035 }
3036 Out << ")";
3037 }
3038 Out << ")";
3039 if (!VI.name().empty())
3040 Out << " ; guid = " << VI.getGUID();
3041 Out << "\n";
3042}
3043
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003044static void printMetadataIdentifier(StringRef Name,
3045 formatted_raw_ostream &Out) {
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003046 if (Name.empty()) {
3047 Out << "<empty name> ";
3048 } else {
Filipe Cabecinhas1ac0d2d2015-06-02 21:25:00 +00003049 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3050 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003051 Out << Name[0];
3052 else
3053 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3054 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3055 unsigned char C = Name[i];
Guy Benyei83c74e92013-02-12 21:21:59 +00003056 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3057 C == '.' || C == '_')
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003058 Out << C;
3059 else
3060 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3061 }
3062 }
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003063}
3064
3065void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3066 Out << '!';
3067 printMetadataIdentifier(NMD->getName(), Out);
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003068 Out << " = !{";
Chris Lattner2c48c642009-12-31 01:54:05 +00003069 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
Filipe Cabecinhas1ac0d2d2015-06-02 21:25:00 +00003070 if (i)
3071 Out << ", ";
Reid Kleckner6d353342017-08-23 20:31:27 +00003072
3073 // Write DIExpressions inline.
3074 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3075 MDNode *Op = NMD->getOperand(i);
3076 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3077 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3078 continue;
3079 }
3080
3081 int Slot = Machine.getMetadataSlot(Op);
Dan Gohman0a54da22010-09-09 20:53:58 +00003082 if (Slot == -1)
3083 Out << "<badref>";
3084 else
3085 Out << '!' << Slot;
Chris Lattner2c48c642009-12-31 01:54:05 +00003086 }
3087 Out << "}\n";
3088}
3089
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003090static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
Dan Gohmane2745262009-08-12 17:23:50 +00003091 formatted_raw_ostream &Out) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003092 switch (Vis) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003093 case GlobalValue::DefaultVisibility: break;
3094 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3095 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3096 }
3097}
3098
Rafael Espindolae4b02312018-01-11 22:15:05 +00003099static void PrintDSOLocation(const GlobalValue &GV,
3100 formatted_raw_ostream &Out) {
Rafael Espindola9fbc0402018-01-18 02:08:23 +00003101 // GVs with local linkage or non default visibility are implicitly dso_local,
3102 // so we don't print it.
3103 bool Implicit = GV.hasLocalLinkage() ||
3104 (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3105 if (GV.isDSOLocal() && !Implicit)
Sean Fertilec70d28b2017-10-26 15:00:26 +00003106 Out << "dso_local ";
3107}
3108
Nico Rieck7157bb72014-01-14 15:22:47 +00003109static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3110 formatted_raw_ostream &Out) {
3111 switch (SCT) {
3112 case GlobalValue::DefaultStorageClass: break;
3113 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3114 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3115 }
3116}
3117
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003118static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3119 formatted_raw_ostream &Out) {
3120 switch (TLM) {
3121 case GlobalVariable::NotThreadLocal:
3122 break;
3123 case GlobalVariable::GeneralDynamicTLSModel:
3124 Out << "thread_local ";
3125 break;
3126 case GlobalVariable::LocalDynamicTLSModel:
3127 Out << "thread_local(localdynamic) ";
3128 break;
3129 case GlobalVariable::InitialExecTLSModel:
3130 Out << "thread_local(initialexec) ";
3131 break;
3132 case GlobalVariable::LocalExecTLSModel:
3133 Out << "thread_local(localexec) ";
3134 break;
3135 }
3136}
3137
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003138static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3139 switch (UA) {
3140 case GlobalVariable::UnnamedAddr::None:
3141 return "";
3142 case GlobalVariable::UnnamedAddr::Local:
3143 return "local_unnamed_addr";
3144 case GlobalVariable::UnnamedAddr::Global:
3145 return "unnamed_addr";
3146 }
Aaron Ballman2b9fa3f2016-06-15 15:27:53 +00003147 llvm_unreachable("Unknown UnnamedAddr");
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003148}
3149
Rafael Espindola83a362c2015-01-06 22:55:16 +00003150static void maybePrintComdat(formatted_raw_ostream &Out,
3151 const GlobalObject &GO) {
3152 const Comdat *C = GO.getComdat();
3153 if (!C)
3154 return;
3155
3156 if (isa<GlobalVariable>(GO))
3157 Out << ',';
3158 Out << " comdat";
3159
3160 if (GO.getName() == C->getName())
3161 return;
3162
3163 Out << '(';
3164 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3165 Out << ')';
3166}
3167
Chris Lattner7bfee412001-10-29 16:05:51 +00003168void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
Dan Gohman5ded1422010-01-29 23:12:36 +00003169 if (GV->isMaterializable())
3170 Out << "; Materializable\n";
3171
Dan Gohmana2489d12010-07-20 23:55:01 +00003172 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
Dan Gohman466876b2009-08-12 23:32:33 +00003173 Out << " = ";
Chris Lattner37798642001-09-18 04:01:05 +00003174
Chris Lattner1508d3f2008-08-19 05:16:28 +00003175 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3176 Out << "external ";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003177
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003178 Out << getLinkageNameWithSpace(GV->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003179 PrintDSOLocation(*GV, Out);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003180 PrintVisibility(GV->getVisibility(), Out);
Nico Rieck7157bb72014-01-14 15:22:47 +00003181 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003182 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003183 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3184 if (!UA.empty())
3185 Out << UA << ' ';
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00003186
Chris Lattnerac161bf2009-01-02 07:01:27 +00003187 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3188 Out << "addrspace(" << AddressSpace << ") ";
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003189 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
Misha Brukmana6619a92004-06-21 21:53:56 +00003190 Out << (GV->isConstant() ? "constant " : "global ");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003191 TypePrinter.print(GV->getValueType(), Out);
Chris Lattner37798642001-09-18 04:01:05 +00003192
Dan Gohman81313fd2008-09-14 17:21:12 +00003193 if (GV->hasInitializer()) {
3194 Out << ' ';
Devang Patel983c6b12009-07-08 21:44:25 +00003195 writeOperand(GV->getInitializer(), false);
Dan Gohman81313fd2008-09-14 17:21:12 +00003196 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003197
Chris Lattner9380b812010-07-07 23:16:37 +00003198 if (GV->hasSection()) {
3199 Out << ", section \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00003200 printEscapedString(GV->getSection(), Out);
Chris Lattner9380b812010-07-07 23:16:37 +00003201 Out << '"';
3202 }
Rafael Espindola83a362c2015-01-06 22:55:16 +00003203 maybePrintComdat(Out, *GV);
Chris Lattner4b96c542005-11-12 00:10:19 +00003204 if (GV->getAlignment())
Chris Lattnerf8a974d2005-11-06 06:48:53 +00003205 Out << ", align " << GV->getAlignment();
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003206
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003207 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3208 GV->getAllMetadata(MDs);
3209 printMetadataAttachments(MDs, ", ");
3210
Javed Absarf3d79042017-05-11 12:28:08 +00003211 auto Attrs = GV->getAttributes();
3212 if (Attrs.hasAttributes())
3213 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3214
Chris Lattner113f4f42002-06-25 16:13:24 +00003215 printInfoComment(*GV);
Chris Lattnerda975502001-09-10 07:58:01 +00003216}
3217
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003218void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3219 if (GIS->isMaterializable())
Dan Gohman5ded1422010-01-29 23:12:36 +00003220 Out << "; Materializable\n";
3221
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003222 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
Rafael Espindola54fc2982015-06-17 17:53:31 +00003223 Out << " = ";
3224
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003225 Out << getLinkageNameWithSpace(GIS->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003226 PrintDSOLocation(*GIS, Out);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003227 PrintVisibility(GIS->getVisibility(), Out);
3228 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3229 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003230 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3231 if (!UA.empty())
3232 Out << UA << ' ';
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003233
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003234 if (isa<GlobalAlias>(GIS))
3235 Out << "alias ";
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003236 else if (isa<GlobalIFunc>(GIS))
3237 Out << "ifunc ";
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003238 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003239 llvm_unreachable("Not an alias or ifunc!");
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003240
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003241 TypePrinter.print(GIS->getValueType(), Out);
David Blaikie2f408302015-09-11 03:22:04 +00003242
3243 Out << ", ";
3244
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003245 const Constant *IS = GIS->getIndirectSymbol();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003246
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003247 if (!IS) {
3248 TypePrinter.print(GIS->getType(), Out);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003249 Out << " <<NULL ALIASEE>>";
Jay Foad92c19132011-08-01 12:48:54 +00003250 } else {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003251 writeOperand(IS, !isa<ConstantExpr>(IS));
Jay Foad92c19132011-08-01 12:48:54 +00003252 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003253
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003254 printInfoComment(*GIS);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003255 Out << '\n';
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003256}
3257
David Majnemerdad0a642014-06-27 18:19:56 +00003258void AssemblyWriter::printComdat(const Comdat *C) {
3259 C->print(Out);
3260}
3261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003262void AssemblyWriter::printTypeIdentities() {
Roman Tereshind96de6f2018-03-22 21:29:07 +00003263 if (TypePrinter.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003264 return;
Andrew Trickec4b6e72011-09-30 19:48:58 +00003265
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003266 Out << '\n';
Andrew Trickec4b6e72011-09-30 19:48:58 +00003267
Chris Lattner3243ea12009-03-01 00:03:38 +00003268 // Emit all numbered types.
Roman Tereshind96de6f2018-03-22 21:29:07 +00003269 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3270 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3271 Out << '%' << I << " = type ";
Andrew Trickec4b6e72011-09-30 19:48:58 +00003272
Chris Lattner3243ea12009-03-01 00:03:38 +00003273 // Make sure we print out at least one level of the type structure, so
3274 // that we do not get %2 = type %2
Roman Tereshind96de6f2018-03-22 21:29:07 +00003275 TypePrinter.printStructBody(NumberedTypes[I], Out);
Dan Gohman69273e62009-08-12 23:54:22 +00003276 Out << '\n';
Chris Lattner3243ea12009-03-01 00:03:38 +00003277 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00003278
Roman Tereshind96de6f2018-03-22 21:29:07 +00003279 auto &NamedTypes = TypePrinter.getNamedTypes();
3280 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3281 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003282 Out << " = type ";
Reid Spencere7e96712004-05-25 08:53:40 +00003283
3284 // Make sure we print out at least one level of the type structure, so
3285 // that we do not get %FILE = type %FILE
Roman Tereshind96de6f2018-03-22 21:29:07 +00003286 TypePrinter.printStructBody(NamedTypes[I], Out);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003287 Out << '\n';
Reid Spencere7e96712004-05-25 08:53:40 +00003288 }
Reid Spencer32af9e82007-01-06 07:24:44 +00003289}
3290
Misha Brukmanc566ca362004-03-02 00:22:19 +00003291/// printFunction - Print all aspects of a function.
Chris Lattner113f4f42002-06-25 16:13:24 +00003292void AssemblyWriter::printFunction(const Function *F) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003293 // Print out the return type and name.
3294 Out << '\n';
Chris Lattner379a8d22003-04-16 20:28:45 +00003295
Misha Brukmana6619a92004-06-21 21:53:56 +00003296 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003297
Dan Gohman5ded1422010-01-29 23:12:36 +00003298 if (F->isMaterializable())
3299 Out << "; Materializable\n";
3300
Reid Klecknerb5180542017-03-21 16:57:19 +00003301 const AttributeList &Attrs = F->getAttributes();
3302 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003303 AttributeSet AS = Attrs.getFnAttributes();
Rafael Espindolacbf5a7a2013-05-01 13:07:03 +00003304 std::string AttrStr;
3305
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003306 for (const Attribute &Attr : AS) {
Rafael Espindolacbf5a7a2013-05-01 13:07:03 +00003307 if (!Attr.isStringAttribute()) {
3308 if (!AttrStr.empty()) AttrStr += ' ';
3309 AttrStr += Attr.getAsString();
3310 }
3311 }
3312
Bill Wendling847a5c32013-04-16 20:55:47 +00003313 if (!AttrStr.empty())
3314 Out << "; Function Attrs: " << AttrStr << '\n';
3315 }
3316
Peter Collingbourne21521892016-06-21 23:42:48 +00003317 Machine.incorporateFunction(F);
3318
3319 if (F->isDeclaration()) {
3320 Out << "declare";
3321 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3322 F->getAllMetadata(MDs);
3323 printMetadataAttachments(MDs, " ");
3324 Out << ' ';
3325 } else
Reid Spencer7ce2d2a2006-12-29 20:29:48 +00003326 Out << "define ";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003327
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003328 Out << getLinkageNameWithSpace(F->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003329 PrintDSOLocation(*F, Out);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003330 PrintVisibility(F->getVisibility(), Out);
Nico Rieck7157bb72014-01-14 15:22:47 +00003331 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
Chris Lattner379a8d22003-04-16 20:28:45 +00003332
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003333 // Print the calling convention.
Micah Villmow857186d2012-09-13 15:11:12 +00003334 if (F->getCallingConv() != CallingConv::C) {
3335 PrintCallingConv(F->getCallingConv(), Out);
3336 Out << " ";
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003337 }
3338
Chris Lattner229907c2011-07-18 04:54:35 +00003339 FunctionType *FT = F->getFunctionType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003340 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3341 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003342 TypePrinter.print(F->getReturnType(), Out);
Chris Lattner585297e82008-08-19 05:26:17 +00003343 Out << ' ';
Dan Gohmana2489d12010-07-20 23:55:01 +00003344 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
Misha Brukmana6619a92004-06-21 21:53:56 +00003345 Out << '(';
Chris Lattnerfee714f2001-09-07 16:36:04 +00003346
Chris Lattner7bfee412001-10-29 16:05:51 +00003347 // Loop over the arguments, printing them...
Justin Bognerd7d1a722015-09-27 22:38:50 +00003348 if (F->isDeclaration() && !IsForDebug) {
Justin Bogner58e08232015-09-02 17:54:41 +00003349 // We're only interested in the type here - don't print argument names.
3350 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
Chris Lattner82738fe2007-04-18 00:57:22 +00003351 // Insert commas as we go... the first arg doesn't get a comma
Justin Bogner58e08232015-09-02 17:54:41 +00003352 if (I)
3353 Out << ", ";
3354 // Output type...
3355 TypePrinter.print(FT->getParamType(I), Out);
3356
Reid Kleckner6652a522017-04-28 18:37:16 +00003357 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3358 if (ArgAttrs.hasAttributes())
3359 Out << ' ' << ArgAttrs.getAsString();
Chris Lattner82738fe2007-04-18 00:57:22 +00003360 }
3361 } else {
Justin Bogner58e08232015-09-02 17:54:41 +00003362 // The arguments are meaningful here, print them in detail.
Justin Bogner58e08232015-09-02 17:54:41 +00003363 for (const Argument &Arg : F->args()) {
Chris Lattner82738fe2007-04-18 00:57:22 +00003364 // Insert commas as we go... the first arg doesn't get a comma
Reid Kleckner6652a522017-04-28 18:37:16 +00003365 if (Arg.getArgNo() != 0)
Justin Bogner58e08232015-09-02 17:54:41 +00003366 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003367 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
Chris Lattner82738fe2007-04-18 00:57:22 +00003368 }
Reid Spencer8c4914c2006-12-31 05:24:50 +00003369 }
Chris Lattnerfee714f2001-09-07 16:36:04 +00003370
3371 // Finish printing arguments...
Chris Lattner113f4f42002-06-25 16:13:24 +00003372 if (FT->isVarArg()) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003373 if (FT->getNumParams()) Out << ", ";
3374 Out << "..."; // Output varargs portion of signature!
Chris Lattnerfee714f2001-09-07 16:36:04 +00003375 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003376 Out << ')';
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003377 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3378 if (!UA.empty())
3379 Out << ' ' << UA;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003380 // We print the function address space if it is non-zero or if we are writing
3381 // a module with a non-zero program address space or if there is no valid
3382 // Module* so that the file can be parsed without the datalayout string.
3383 const Module *Mod = F->getParent();
3384 if (F->getAddressSpace() != 0 || !Mod ||
3385 Mod->getDataLayout().getProgramAddressSpace() != 0)
3386 Out << " addrspace(" << F->getAddressSpace() << ")";
Reid Klecknerb5180542017-03-21 16:57:19 +00003387 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
Bill Wendling04945972013-04-29 23:48:06 +00003388 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
Chris Lattner9380b812010-07-07 23:16:37 +00003389 if (F->hasSection()) {
3390 Out << " section \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00003391 printEscapedString(F->getSection(), Out);
Chris Lattner9380b812010-07-07 23:16:37 +00003392 Out << '"';
3393 }
Rafael Espindola83a362c2015-01-06 22:55:16 +00003394 maybePrintComdat(Out, *F);
Chris Lattnerf8a974d2005-11-06 06:48:53 +00003395 if (F->getAlignment())
3396 Out << " align " << F->getAlignment();
Gordon Henriksend930f912008-08-17 18:44:35 +00003397 if (F->hasGC())
3398 Out << " gc \"" << F->getGC() << '"';
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003399 if (F->hasPrefixData()) {
3400 Out << " prefix ";
3401 writeOperand(F->getPrefixData(), true);
3402 }
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003403 if (F->hasPrologueData()) {
3404 Out << " prologue ";
3405 writeOperand(F->getPrologueData(), true);
3406 }
David Majnemer7fddecc2015-06-17 20:52:32 +00003407 if (F->hasPersonalityFn()) {
3408 Out << " personality ";
3409 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3410 }
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003411
Reid Spencer5301e7c2007-01-30 20:08:39 +00003412 if (F->isDeclaration()) {
Chris Lattnerfb483622010-09-02 22:52:10 +00003413 Out << '\n';
Chris Lattnerb2f02e52002-05-06 03:00:40 +00003414 } else {
Peter Collingbourne21521892016-06-21 23:42:48 +00003415 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3416 F->getAllMetadata(MDs);
3417 printMetadataAttachments(MDs, " ");
3418
Chris Lattnerfb483622010-09-02 22:52:10 +00003419 Out << " {";
3420 // Output all of the function's basic blocks.
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003421 for (const BasicBlock &BB : *F)
3422 printBasicBlock(&BB);
Chris Lattnerfee714f2001-09-07 16:36:04 +00003423
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003424 // Output the function's use-lists.
3425 printUseLists(F);
3426
Misha Brukmana6619a92004-06-21 21:53:56 +00003427 Out << "}\n";
Chris Lattnerfee714f2001-09-07 16:36:04 +00003428 }
3429
Reid Spencer16f2f7f2004-05-26 07:18:52 +00003430 Machine.purgeFunction();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003431}
3432
Misha Brukmanc566ca362004-03-02 00:22:19 +00003433/// printArgument - This member is called for every argument that is passed into
3434/// the function. Simply print it out
Reid Kleckner6652a522017-04-28 18:37:16 +00003435void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00003436 // Output type...
Chris Lattnere101c442009-02-28 21:26:53 +00003437 TypePrinter.print(Arg->getType(), Out);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003438
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003439 // Output parameter attributes list
Reid Kleckner6652a522017-04-28 18:37:16 +00003440 if (Attrs.hasAttributes())
3441 Out << ' ' << Attrs.getAsString();
Reid Spencer8c4914c2006-12-31 05:24:50 +00003442
Chris Lattner2f7c9632001-06-06 20:29:01 +00003443 // Output name, if available...
Chris Lattner033935d2008-08-17 04:40:13 +00003444 if (Arg->hasName()) {
3445 Out << ' ';
3446 PrintLLVMName(Out, Arg);
3447 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003448}
3449
Misha Brukmanc566ca362004-03-02 00:22:19 +00003450/// printBasicBlock - This member is called for each basic block in a method.
Chris Lattner7bfee412001-10-29 16:05:51 +00003451void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003452 if (BB->hasName()) { // Print out the label if it exists...
Chris Lattner033935d2008-08-17 04:40:13 +00003453 Out << "\n";
Daniel Dunbare03eecb2009-07-25 23:55:21 +00003454 PrintLLVMName(Out, BB->getName(), LabelPrefix);
Chris Lattner033935d2008-08-17 04:40:13 +00003455 Out << ':';
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003456 } else if (!BB->use_empty()) { // Don't print block # of no uses...
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003457 Out << "\n; <label>:";
Chris Lattner5e043322007-01-11 03:54:27 +00003458 int Slot = Machine.getLocalSlot(BB);
Chris Lattner757ee0b2004-06-09 19:41:19 +00003459 if (Slot != -1)
Evgeniy Stepanove257f0f2016-01-27 21:53:08 +00003460 Out << Slot << ":";
Chris Lattner757ee0b2004-06-09 19:41:19 +00003461 else
Misha Brukmana6619a92004-06-21 21:53:56 +00003462 Out << "<badref>";
Chris Lattner58185f22002-10-02 19:38:55 +00003463 }
Chris Lattner2447ef52003-11-20 00:09:43 +00003464
Craig Topperc6207612014-04-09 06:08:46 +00003465 if (!BB->getParent()) {
Chris Lattneree97b8b2009-08-17 15:48:08 +00003466 Out.PadToColumn(50);
Dan Gohmane2745262009-08-12 17:23:50 +00003467 Out << "; Error: Block without parent!";
3468 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
Chris Lattnerfb483622010-09-02 22:52:10 +00003469 // Output predecessors for the block.
Chris Lattneree97b8b2009-08-17 15:48:08 +00003470 Out.PadToColumn(50);
Dan Gohmane2745262009-08-12 17:23:50 +00003471 Out << ";";
Gabor Greif6c6b2fd2010-03-25 23:25:28 +00003472 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003473
Chris Lattnerff834c02008-04-22 02:45:44 +00003474 if (PI == PE) {
3475 Out << " No predecessors!";
3476 } else {
Dan Gohman81313fd2008-09-14 17:21:12 +00003477 Out << " preds = ";
Chris Lattnerff834c02008-04-22 02:45:44 +00003478 writeOperand(*PI, false);
3479 for (++PI; PI != PE; ++PI) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003480 Out << ", ";
Chris Lattner78e2e8b2006-12-06 06:24:27 +00003481 writeOperand(*PI, false);
Chris Lattner00211f12003-11-16 22:59:57 +00003482 }
Chris Lattner58185f22002-10-02 19:38:55 +00003483 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003484 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003485
Chris Lattnerff834c02008-04-22 02:45:44 +00003486 Out << "\n";
Chris Lattner2f7c9632001-06-06 20:29:01 +00003487
Misha Brukmana6619a92004-06-21 21:53:56 +00003488 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003489
Chris Lattnerfee714f2001-09-07 16:36:04 +00003490 // Output all of the instructions in the basic block...
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003491 for (const Instruction &I : *BB) {
3492 printInstructionLine(I);
Dan Gohmana4f709e2009-07-13 18:27:59 +00003493 }
Chris Lattner96cdd272004-03-08 18:51:45 +00003494
Misha Brukmana6619a92004-06-21 21:53:56 +00003495 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003496}
3497
Daniel Maleaded9f932013-05-08 20:38:31 +00003498/// printInstructionLine - Print an instruction and a newline character.
3499void AssemblyWriter::printInstructionLine(const Instruction &I) {
3500 printInstruction(I);
3501 Out << '\n';
3502}
3503
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003504/// printGCRelocateComment - print comment after call to the gc.relocate
3505/// intrinsic indicating base and derived pointer names.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003506void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003507 Out << " ; (";
Manuel Jacob83eefa62016-01-05 04:03:00 +00003508 writeOperand(Relocate.getBasePtr(), false);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003509 Out << ", ";
Manuel Jacob83eefa62016-01-05 04:03:00 +00003510 writeOperand(Relocate.getDerivedPtr(), false);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003511 Out << ")";
3512}
3513
Misha Brukmanc566ca362004-03-02 00:22:19 +00003514/// printInfoComment - Print a little comment after the instruction indicating
3515/// which slot it occupies.
Chris Lattner113f4f42002-06-25 16:13:24 +00003516void AssemblyWriter::printInfoComment(const Value &V) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00003517 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3518 printGCRelocateComment(*Relocate);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003519
Bill Wendling847a5c32013-04-16 20:55:47 +00003520 if (AnnotationWriter)
Dan Gohmane34890f2010-02-10 20:41:46 +00003521 AnnotationWriter->printInfoComment(V, Out);
Chris Lattner862e3382001-10-13 06:42:36 +00003522}
3523
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003524static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3525 raw_ostream &Out) {
3526 // We print the address space of the call if it is non-zero.
3527 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3528 bool PrintAddrSpace = CallAddrSpace != 0;
3529 if (!PrintAddrSpace) {
3530 const Module *Mod = getModuleFromVal(I);
3531 // We also print it if it is zero but not equal to the program address space
3532 // or if we can't find a valid Module* to make it possible to parse
3533 // the resulting file even without a datalayout string.
3534 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3535 PrintAddrSpace = true;
3536 }
3537 if (PrintAddrSpace)
3538 Out << " addrspace(" << CallAddrSpace << ")";
3539}
3540
Reid Spencere7141c82006-08-28 01:02:49 +00003541// This member is called for each Instruction in a function..
Chris Lattner113f4f42002-06-25 16:13:24 +00003542void AssemblyWriter::printInstruction(const Instruction &I) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003543 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003544
Dan Gohman466876b2009-08-12 23:32:33 +00003545 // Print out indentation for an instruction.
Dan Gohmanb4583b12009-08-13 01:41:52 +00003546 Out << " ";
Chris Lattner2f7c9632001-06-06 20:29:01 +00003547
3548 // Print out name if it exists...
Chris Lattner033935d2008-08-17 04:40:13 +00003549 if (I.hasName()) {
3550 PrintLLVMName(Out, &I);
3551 Out << " = ";
Chris Lattner031560c2009-12-29 07:25:48 +00003552 } else if (!I.getType()->isVoidTy()) {
Chris Lattnerb25e5ea2008-08-29 17:19:30 +00003553 // Print out the def slot taken.
3554 int SlotNum = Machine.getLocalSlot(&I);
3555 if (SlotNum == -1)
3556 Out << "<badref> = ";
3557 else
3558 Out << '%' << SlotNum << " = ";
Chris Lattner033935d2008-08-17 04:40:13 +00003559 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00003560
Reid Kleckner5772b772014-04-24 20:14:34 +00003561 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3562 if (CI->isMustTailCall())
3563 Out << "musttail ";
3564 else if (CI->isTailCall())
3565 Out << "tail ";
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00003566 else if (CI->isNoTailCall())
3567 Out << "notail ";
Reid Kleckner5772b772014-04-24 20:14:34 +00003568 }
Chris Lattner504f9242003-09-08 17:45:59 +00003569
Chris Lattner2f7c9632001-06-06 20:29:01 +00003570 // Print out the opcode...
Misha Brukmana6619a92004-06-21 21:53:56 +00003571 Out << I.getOpcodeName();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003572
Eli Friedman02e737b2011-08-12 22:50:01 +00003573 // If this is an atomic load or store, print out the atomic marker.
3574 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
3575 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3576 Out << " atomic";
3577
Tim Northover420a2162014-06-13 14:24:07 +00003578 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3579 Out << " weak";
3580
Eli Friedman02e737b2011-08-12 22:50:01 +00003581 // If this is a volatile operation, print out the volatile marker.
3582 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
3583 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3584 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3585 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3586 Out << " volatile";
3587
Dan Gohman9c7f8082009-07-27 16:11:46 +00003588 // Print out optimization information.
3589 WriteOptimizationInfo(Out, &I);
3590
Reid Spencer45e52392006-12-03 06:27:29 +00003591 // Print out the compare instruction predicates
Nate Begemand2195702008-05-12 19:01:56 +00003592 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
Tim Northoverde3aea0412016-08-17 20:25:25 +00003593 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
Reid Spencer45e52392006-12-03 06:27:29 +00003594
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003595 // Print out the atomicrmw operation
3596 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
Matt Arsenaultb02ba992018-10-02 23:44:11 +00003597 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003598
Chris Lattner2f7c9632001-06-06 20:29:01 +00003599 // Print out the type of the operands...
Craig Topperc6207612014-04-09 06:08:46 +00003600 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
Chris Lattner2f7c9632001-06-06 20:29:01 +00003601
3602 // Special case conditional branches to swizzle the condition out to the front
Gabor Greifcab008f2009-02-09 15:45:06 +00003603 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
David Blaikieb78e9e52013-02-11 01:16:51 +00003604 const BranchInst &BI(cast<BranchInst>(I));
Dan Gohman81313fd2008-09-14 17:21:12 +00003605 Out << ' ';
Gabor Greifcab008f2009-02-09 15:45:06 +00003606 writeOperand(BI.getCondition(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003607 Out << ", ";
Gabor Greifcab008f2009-02-09 15:45:06 +00003608 writeOperand(BI.getSuccessor(0), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003609 Out << ", ";
Gabor Greifcab008f2009-02-09 15:45:06 +00003610 writeOperand(BI.getSuccessor(1), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003611
Chris Lattner8d48df22002-04-13 18:34:38 +00003612 } else if (isa<SwitchInst>(I)) {
David Blaikieb78e9e52013-02-11 01:16:51 +00003613 const SwitchInst& SI(cast<SwitchInst>(I));
Chris Lattner3ed871f2009-10-27 19:13:16 +00003614 // Special case switch instruction to get formatting nice and correct.
Dan Gohman81313fd2008-09-14 17:21:12 +00003615 Out << ' ';
Eli Friedman95031ed2011-09-29 20:21:17 +00003616 writeOperand(SI.getCondition(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003617 Out << ", ";
Eli Friedman95031ed2011-09-29 20:21:17 +00003618 writeOperand(SI.getDefaultDest(), true);
Chris Lattner82ff9232008-08-23 22:52:27 +00003619 Out << " [";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003620 for (auto Case : SI.cases()) {
Dan Gohmanb4583b12009-08-13 01:41:52 +00003621 Out << "\n ";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003622 writeOperand(Case.getCaseValue(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003623 Out << ", ";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003624 writeOperand(Case.getCaseSuccessor(), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003625 }
Dan Gohmanb4583b12009-08-13 01:41:52 +00003626 Out << "\n ]";
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003627 } else if (isa<IndirectBrInst>(I)) {
3628 // Special case indirectbr instruction to get formatting nice and correct.
Chris Lattner3ed871f2009-10-27 19:13:16 +00003629 Out << ' ';
3630 writeOperand(Operand, true);
Dan Gohman43c57402009-10-30 02:01:10 +00003631 Out << ", [";
Andrew Trickec4b6e72011-09-30 19:48:58 +00003632
Chris Lattner3ed871f2009-10-27 19:13:16 +00003633 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3634 if (i != 1)
3635 Out << ", ";
3636 writeOperand(I.getOperand(i), true);
3637 }
3638 Out << ']';
Jay Foad372ad642011-06-20 14:18:48 +00003639 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003640 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003641 TypePrinter.print(I.getType(), Out);
Misha Brukmana6619a92004-06-21 21:53:56 +00003642 Out << ' ';
Chris Lattner2f7c9632001-06-06 20:29:01 +00003643
Jay Foad372ad642011-06-20 14:18:48 +00003644 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003645 if (op) Out << ", ";
Dan Gohman81313fd2008-09-14 17:21:12 +00003646 Out << "[ ";
Jay Foad372ad642011-06-20 14:18:48 +00003647 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3648 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
Chris Lattner931ef3b2001-06-11 15:04:20 +00003649 }
Dan Gohmana76f0f72008-05-31 19:12:39 +00003650 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003651 Out << ' ';
Dan Gohmana76f0f72008-05-31 19:12:39 +00003652 writeOperand(I.getOperand(0), true);
3653 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3654 Out << ", " << *i;
3655 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003656 Out << ' ';
3657 writeOperand(I.getOperand(0), true); Out << ", ";
Dan Gohmana76f0f72008-05-31 19:12:39 +00003658 writeOperand(I.getOperand(1), true);
3659 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3660 Out << ", " << *i;
Bill Wendlingfae14752011-08-12 20:24:12 +00003661 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3662 Out << ' ';
3663 TypePrinter.print(I.getType(), Out);
David Majnemer7fddecc2015-06-17 20:52:32 +00003664 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3665 Out << '\n';
Bill Wendlingfae14752011-08-12 20:24:12 +00003666
3667 if (LPI->isCleanup())
3668 Out << " cleanup";
3669
3670 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3671 if (i != 0 || LPI->isCleanup()) Out << "\n";
3672 if (LPI->isCatch(i))
3673 Out << " catch ";
3674 else
3675 Out << " filter ";
3676
3677 writeOperand(LPI->getClause(i), true);
3678 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003679 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3680 Out << " within ";
3681 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
David Majnemer654e1302015-07-31 17:58:14 +00003682 Out << " [";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003683 unsigned Op = 0;
3684 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3685 if (Op > 0)
3686 Out << ", ";
3687 writeOperand(PadBB, /*PrintType=*/true);
3688 ++Op;
3689 }
3690 Out << "] unwind ";
3691 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3692 writeOperand(UnwindDest, /*PrintType=*/true);
3693 else
3694 Out << "to caller";
3695 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3696 Out << " within ";
3697 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3698 Out << " [";
3699 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
David Majnemer654e1302015-07-31 17:58:14 +00003700 ++Op) {
3701 if (Op > 0)
3702 Out << ", ";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003703 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
David Majnemer654e1302015-07-31 17:58:14 +00003704 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003705 Out << ']';
Devang Patel59643e52008-02-23 00:35:18 +00003706 } else if (isa<ReturnInst>(I) && !Operand) {
3707 Out << " void";
David Majnemer0bc0eef2015-08-15 02:46:08 +00003708 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003709 Out << " from ";
3710 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
David Majnemer0bc0eef2015-08-15 02:46:08 +00003711
3712 Out << " to ";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003713 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
David Majnemer654e1302015-07-31 17:58:14 +00003714 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003715 Out << " from ";
3716 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
David Majnemer654e1302015-07-31 17:58:14 +00003717
3718 Out << " unwind ";
3719 if (CRI->hasUnwindDest())
David Majnemer8a1c45d2015-12-12 05:38:55 +00003720 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003721 else
3722 Out << "to caller";
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003723 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3724 // Print the calling convention being used.
Micah Villmow857186d2012-09-13 15:11:12 +00003725 if (CI->getCallingConv() != CallingConv::C) {
3726 Out << " ";
3727 PrintCallingConv(CI->getCallingConv(), Out);
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003728 }
3729
Gabor Greifc9a92512010-06-23 13:09:06 +00003730 Operand = CI->getCalledValue();
Ahmed Bougachaaa9fe532016-12-21 23:26:13 +00003731 FunctionType *FTy = CI->getFunctionType();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003732 Type *RetTy = FTy->getReturnType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003733 const AttributeList &PAL = CI->getAttributes();
Chris Lattner2f2d9472001-11-06 21:28:12 +00003734
Reid Klecknerb5180542017-03-21 16:57:19 +00003735 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3736 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
Devang Patel221fe422008-09-29 20:49:50 +00003737
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003738 // Only print addrspace(N) if necessary:
3739 maybePrintCallAddrSpace(Operand, &I, Out);
3740
Chris Lattner463d6a52003-08-05 15:34:45 +00003741 // If possible, print out the short form of the call instruction. We can
Chris Lattner6915f8f2002-04-07 22:49:37 +00003742 // only do this if the first argument is a pointer to a nonvararg function,
Chris Lattner463d6a52003-08-05 15:34:45 +00003743 // and if the return type is not a pointer to a function.
Chris Lattner2f2d9472001-11-06 21:28:12 +00003744 //
Dan Gohman81313fd2008-09-14 17:21:12 +00003745 Out << ' ';
David Blaikie23af6482015-04-16 23:24:18 +00003746 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3747 Out << ' ';
3748 writeOperand(Operand, false);
Misha Brukmana6619a92004-06-21 21:53:56 +00003749 Out << '(';
Gabor Greifc9a92512010-06-23 13:09:06 +00003750 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3751 if (op > 0)
Dan Gohman81313fd2008-09-14 17:21:12 +00003752 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003753 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
Chris Lattner2f7c9632001-06-06 20:29:01 +00003754 }
Reid Kleckner83498642014-08-26 00:33:28 +00003755
3756 // Emit an ellipsis if this is a musttail call in a vararg function. This
3757 // is only to aid readability, musttail calls forward varargs by default.
3758 if (CI->isMustTailCall() && CI->getParent() &&
3759 CI->getParent()->getParent() &&
3760 CI->getParent()->getParent()->isVarArg())
3761 Out << ", ...";
3762
Dan Gohman81313fd2008-09-14 17:21:12 +00003763 Out << ')';
Reid Klecknerb5180542017-03-21 16:57:19 +00003764 if (PAL.hasAttributes(AttributeList::FunctionIndex))
Bill Wendlinga0323742013-02-22 09:09:42 +00003765 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003766
3767 writeOperandBundles(CI);
Chris Lattner113f4f42002-06-25 16:13:24 +00003768 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00003769 Operand = II->getCalledValue();
Ahmed Bougachaaa9fe532016-12-21 23:26:13 +00003770 FunctionType *FTy = II->getFunctionType();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003771 Type *RetTy = FTy->getReturnType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003772 const AttributeList &PAL = II->getAttributes();
Chris Lattner463d6a52003-08-05 15:34:45 +00003773
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003774 // Print the calling convention being used.
Micah Villmow857186d2012-09-13 15:11:12 +00003775 if (II->getCallingConv() != CallingConv::C) {
3776 Out << " ";
3777 PrintCallingConv(II->getCallingConv(), Out);
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003778 }
3779
Reid Klecknerb5180542017-03-21 16:57:19 +00003780 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3781 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
Devang Patel221fe422008-09-29 20:49:50 +00003782
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003783 // Only print addrspace(N) if necessary:
3784 maybePrintCallAddrSpace(Operand, &I, Out);
3785
Chris Lattner463d6a52003-08-05 15:34:45 +00003786 // If possible, print out the short form of the invoke instruction. We can
3787 // only do this if the first argument is a pointer to a nonvararg function,
3788 // and if the return type is not a pointer to a function.
3789 //
Dan Gohmanc7e00ba2008-10-15 18:02:08 +00003790 Out << ' ';
David Blaikie445e3fb2015-04-24 19:32:54 +00003791 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3792 Out << ' ';
3793 writeOperand(Operand, false);
Misha Brukmana6619a92004-06-21 21:53:56 +00003794 Out << '(';
Gabor Greifc9a92512010-06-23 13:09:06 +00003795 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00003796 if (op)
Dan Gohman81313fd2008-09-14 17:21:12 +00003797 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003798 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
Chris Lattner862e3382001-10-13 06:42:36 +00003799 }
3800
Dan Gohman81313fd2008-09-14 17:21:12 +00003801 Out << ')';
Reid Klecknerb5180542017-03-21 16:57:19 +00003802 if (PAL.hasAttributes(AttributeList::FunctionIndex))
Bill Wendlinga0323742013-02-22 09:09:42 +00003803 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
Devang Patela05633e2008-09-26 22:53:05 +00003804
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003805 writeOperandBundles(II);
3806
Dan Gohmanb4583b12009-08-13 01:41:52 +00003807 Out << "\n to ";
Chris Lattner862e3382001-10-13 06:42:36 +00003808 writeOperand(II->getNormalDest(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003809 Out << " unwind ";
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003810 writeOperand(II->getUnwindDest(), true);
Victor Hernandez8acf2952009-10-23 21:09:37 +00003811 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003812 Out << ' ';
Reid Kleckner20844032014-01-25 01:24:06 +00003813 if (AI->isUsedWithInAlloca())
David Majnemerc4ab61c2014-03-09 06:41:58 +00003814 Out << "inalloca ";
Manman Ren9bfd0d02016-04-01 21:41:15 +00003815 if (AI->isSwiftError())
3816 Out << "swifterror ";
David Majnemerc4ab61c2014-03-09 06:41:58 +00003817 TypePrinter.print(AI->getAllocatedType(), Out);
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +00003818
3819 // Explicitly write the array size if the code is broken, if it's an array
3820 // allocation, or if the type is not canonical for scalar allocations. The
3821 // latter case prevents the type from mutating when round-tripping through
3822 // assembly.
3823 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3824 !AI->getArraySize()->getType()->isIntegerTy(32)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003825 Out << ", ";
Chris Lattner8d48df22002-04-13 18:34:38 +00003826 writeOperand(AI->getArraySize(), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003827 }
Nate Begeman848622f2005-11-05 09:21:28 +00003828 if (AI->getAlignment()) {
Chris Lattner7aeee3a2005-11-05 21:20:34 +00003829 Out << ", align " << AI->getAlignment();
Nate Begeman848622f2005-11-05 09:21:28 +00003830 }
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003831
3832 unsigned AddrSpace = AI->getType()->getAddressSpace();
3833 if (AddrSpace != 0) {
3834 Out << ", addrspace(" << AddrSpace << ')';
3835 }
Chris Lattner862e3382001-10-13 06:42:36 +00003836 } else if (isa<CastInst>(I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003837 if (Operand) {
3838 Out << ' ';
3839 writeOperand(Operand, true); // Work with broken code
3840 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003841 Out << " to ";
Chris Lattnere101c442009-02-28 21:26:53 +00003842 TypePrinter.print(I.getType(), Out);
Chris Lattner5b337482003-10-18 05:57:43 +00003843 } else if (isa<VAArgInst>(I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003844 if (Operand) {
3845 Out << ' ';
3846 writeOperand(Operand, true); // Work with broken code
3847 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003848 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00003849 TypePrinter.print(I.getType(), Out);
3850 } else if (Operand) { // Print the normal way.
David Blaikiea79ac142015-02-27 21:17:42 +00003851 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
David Blaikie79e6c742015-02-27 19:29:02 +00003852 Out << ' ';
3853 TypePrinter.print(GEP->getSourceElementType(), Out);
3854 Out << ',';
David Blaikiea79ac142015-02-27 21:17:42 +00003855 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3856 Out << ' ';
3857 TypePrinter.print(LI->getType(), Out);
Benjamin Kramer257ed692015-03-02 15:24:41 +00003858 Out << ',';
David Blaikie79e6c742015-02-27 19:29:02 +00003859 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003860
Misha Brukmanb1c93172005-04-21 23:48:37 +00003861 // PrintAllTypes - Instructions who have operands of all the same type
Chris Lattner2f7c9632001-06-06 20:29:01 +00003862 // omit the type from all but the first operand. If the instruction has
3863 // different type operands (for example br), then they are all printed.
3864 bool PrintAllTypes = false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003865 Type *TheType = Operand->getType();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003866
Reid Spencer0cdd04f2007-02-02 13:54:55 +00003867 // Select, Store and ShuffleVector always print all types.
Devang Patelce556d92008-03-04 22:05:14 +00003868 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3869 || isa<ReturnInst>(I)) {
Chris Lattnerdeccfaf2003-04-16 20:20:02 +00003870 PrintAllTypes = true;
3871 } else {
3872 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3873 Operand = I.getOperand(i);
Nuno Lopes04fe2f02009-01-15 18:40:57 +00003874 // note that Operand shouldn't be null, but the test helps make dump()
3875 // more tolerant of malformed IR
Nuno Lopes0971e772009-01-14 17:51:41 +00003876 if (Operand && Operand->getType() != TheType) {
Chris Lattnerdeccfaf2003-04-16 20:20:02 +00003877 PrintAllTypes = true; // We have differing types! Print them all!
3878 break;
3879 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003880 }
3881 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003882
Chris Lattner7bfee412001-10-29 16:05:51 +00003883 if (!PrintAllTypes) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003884 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003885 TypePrinter.print(TheType, Out);
Chris Lattner7bfee412001-10-29 16:05:51 +00003886 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003887
Dan Gohman81313fd2008-09-14 17:21:12 +00003888 Out << ' ';
Chris Lattner113f4f42002-06-25 16:13:24 +00003889 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003890 if (i) Out << ", ";
Chris Lattner113f4f42002-06-25 16:13:24 +00003891 writeOperand(I.getOperand(i), PrintAllTypes);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003892 }
3893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003894
Eli Friedman59b66882011-08-09 23:02:53 +00003895 // Print atomic ordering/alignment for memory operations
3896 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3897 if (LI->isAtomic())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003898 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
Eli Friedman59b66882011-08-09 23:02:53 +00003899 if (LI->getAlignment())
3900 Out << ", align " << LI->getAlignment();
3901 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3902 if (SI->isAtomic())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003903 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
Eli Friedman59b66882011-08-09 23:02:53 +00003904 if (SI->getAlignment())
3905 Out << ", align " << SI->getAlignment();
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003906 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003907 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3908 CXI->getFailureOrdering(), CXI->getSyncScopeID());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003909 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003910 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3911 RMWI->getSyncScopeID());
Eli Friedmanfee02c62011-07-25 23:16:38 +00003912 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003913 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
Christopher Lamb84485702007-04-22 19:24:39 +00003914 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003915
Chris Lattnerc9558df2009-12-28 20:10:43 +00003916 // Print Metadata info.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003917 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
Nick Lewyckyba8ec9a2010-02-25 06:53:04 +00003918 I.getAllMetadata(InstMD);
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003919 printMetadataAttachments(InstMD, ", ");
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003920
3921 // Print a nice comment.
Chris Lattner862e3382001-10-13 06:42:36 +00003922 printInfoComment(I);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003923}
3924
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003925void AssemblyWriter::printMetadataAttachments(
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003926 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3927 StringRef Separator) {
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003928 if (MDs.empty())
3929 return;
3930
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00003931 if (MDNames.empty())
Mehdi Aminib9b50aa2016-01-07 20:14:30 +00003932 MDs[0].second->getContext().getMDKindNames(MDNames);
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00003933
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003934 for (const auto &I : MDs) {
3935 unsigned Kind = I.first;
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003936 Out << Separator;
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003937 if (Kind < MDNames.size()) {
3938 Out << "!";
3939 printMetadataIdentifier(MDNames[Kind], Out);
3940 } else
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003941 Out << "!<unknown kind #" << Kind << ">";
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003942 Out << ' ';
3943 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3944 }
3945}
3946
Daniel Maleaded9f932013-05-08 20:38:31 +00003947void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003948 Out << '!' << Slot << " = ";
Daniel Maleaded9f932013-05-08 20:38:31 +00003949 printMDNodeBody(Node);
Duncan P. N. Exon Smith738889f2015-02-25 22:46:38 +00003950 Out << "\n";
Daniel Maleaded9f932013-05-08 20:38:31 +00003951}
3952
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003953void AssemblyWriter::writeAllMDNodes() {
3954 SmallVector<const MDNode *, 16> Nodes;
Chris Lattnercf4a76e2009-12-31 02:20:11 +00003955 Nodes.resize(Machine.mdn_size());
3956 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3957 I != E; ++I)
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003958 Nodes[I->second] = cast<MDNode>(I->first);
Andrew Trickec4b6e72011-09-30 19:48:58 +00003959
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003960 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
Daniel Maleaded9f932013-05-08 20:38:31 +00003961 writeMDNode(i, Nodes[i]);
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003962 }
3963}
3964
3965void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
Dan Gohmana2489d12010-07-20 23:55:01 +00003966 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003967}
Chris Lattner2f7c9632001-06-06 20:29:01 +00003968
Bill Wendling829b4782013-02-11 08:43:33 +00003969void AssemblyWriter::writeAllAttributeGroups() {
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003970 std::vector<std::pair<AttributeSet, unsigned>> asVec;
Bill Wendling829b4782013-02-11 08:43:33 +00003971 asVec.resize(Machine.as_size());
3972
3973 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3974 I != E; ++I)
3975 asVec[I->second] = *I;
3976
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003977 for (const auto &I : asVec)
3978 Out << "attributes #" << I.second << " = { "
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003979 << I.first.getAsString(true) << " }\n";
Bill Wendling829b4782013-02-11 08:43:33 +00003980}
3981
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003982void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3983 bool IsInFunction = Machine.getFunction();
3984 if (IsInFunction)
3985 Out << " ";
3986
3987 Out << "uselistorder";
3988 if (const BasicBlock *BB =
3989 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3990 Out << "_bb ";
3991 writeOperand(BB->getParent(), false);
3992 Out << ", ";
3993 writeOperand(BB, false);
3994 } else {
3995 Out << " ";
3996 writeOperand(Order.V, true);
3997 }
3998 Out << ", { ";
3999
4000 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4001 Out << Order.Shuffle[0];
4002 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4003 Out << ", " << Order.Shuffle[I];
4004 Out << " }\n";
4005}
4006
4007void AssemblyWriter::printUseLists(const Function *F) {
4008 auto hasMore =
4009 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4010 if (!hasMore())
4011 // Nothing to do.
4012 return;
4013
4014 Out << "\n; uselistorder directives\n";
4015 while (hasMore()) {
4016 printUseListOrder(UseListOrders.back());
4017 UseListOrders.pop_back();
4018 }
4019}
4020
Chris Lattner2f7c9632001-06-06 20:29:01 +00004021//===----------------------------------------------------------------------===//
4022// External Interface declarations
4023//===----------------------------------------------------------------------===//
4024
George Burgess IVe1100f52016-02-02 22:46:49 +00004025void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4026 bool ShouldPreserveUseListOrder,
4027 bool IsForDebug) const {
4028 SlotTracker SlotTable(this->getParent());
4029 formatted_raw_ostream OS(ROS);
4030 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4031 IsForDebug,
4032 ShouldPreserveUseListOrder);
4033 W.printFunction(this);
4034}
4035
Duncan P. N. Exon Smithc4f0a322015-04-15 02:12:41 +00004036void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
Justin Bognerd7d1a722015-09-27 22:38:50 +00004037 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
Chris Lattnere36fd8a2008-08-19 04:26:57 +00004038 SlotTracker SlotTable(this);
Dan Gohmane2745262009-08-12 17:23:50 +00004039 formatted_raw_ostream OS(ROS);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004040 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4041 ShouldPreserveUseListOrder);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004042 W.printModule(this);
Chris Lattner2f7c9632001-06-06 20:29:01 +00004043}
4044
Justin Bognerd7d1a722015-09-27 22:38:50 +00004045void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
Dan Gohman2637cc12010-07-21 23:38:33 +00004046 SlotTracker SlotTable(getParent());
4047 formatted_raw_ostream OS(ROS);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004048 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
Dan Gohman2637cc12010-07-21 23:38:33 +00004049 W.printNamedMDNode(this);
4050}
4051
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +00004052void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4053 bool IsForDebug) const {
4054 Optional<SlotTracker> LocalST;
4055 SlotTracker *SlotTable;
4056 if (auto *ST = MST.getMachine())
4057 SlotTable = ST;
4058 else {
4059 LocalST.emplace(getParent());
4060 SlotTable = &*LocalST;
4061 }
4062
4063 formatted_raw_ostream OS(ROS);
4064 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4065 W.printNamedMDNode(this);
4066}
4067
Justin Bognerd7d1a722015-09-27 22:38:50 +00004068void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
David Majnemerdad0a642014-06-27 18:19:56 +00004069 PrintLLVMName(ROS, getName(), ComdatPrefix);
4070 ROS << " = comdat ";
4071
4072 switch (getSelectionKind()) {
4073 case Comdat::Any:
4074 ROS << "any";
4075 break;
4076 case Comdat::ExactMatch:
4077 ROS << "exactmatch";
4078 break;
4079 case Comdat::Largest:
4080 ROS << "largest";
4081 break;
4082 case Comdat::NoDuplicates:
4083 ROS << "noduplicates";
4084 break;
4085 case Comdat::SameSize:
4086 ROS << "samesize";
4087 break;
4088 }
4089
4090 ROS << '\n';
4091}
4092
Quentin Colombet774b1ef2016-03-07 22:32:42 +00004093void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004094 TypePrinting TP;
4095 TP.print(const_cast<Type*>(this), OS);
Andrew Trickec4b6e72011-09-30 19:48:58 +00004096
Quentin Colombet774b1ef2016-03-07 22:32:42 +00004097 if (NoDetails)
4098 return;
4099
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004100 // If the type is a named struct type, print the body as well.
4101 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
Chris Lattner01beceb2011-08-12 18:07:07 +00004102 if (!STy->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004103 OS << " = type ";
4104 TP.printStructBody(STy, OS);
4105 }
Chris Lattnerc0b4c7b2002-04-08 22:03:40 +00004106}
4107
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004108static bool isReferencingMDNode(const Instruction &I) {
4109 if (const auto *CI = dyn_cast<CallInst>(&I))
4110 if (Function *F = CI->getCalledFunction())
Justin Lebar9cbc3012016-07-28 23:58:15 +00004111 if (F->isIntrinsic())
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004112 for (auto &Op : I.operands())
4113 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4114 if (isa<MDNode>(V->getMetadata()))
4115 return true;
4116 return false;
4117}
4118
Justin Bognerd7d1a722015-09-27 22:38:50 +00004119void Value::print(raw_ostream &ROS, bool IsForDebug) const {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004120 bool ShouldInitializeAllMetadata = false;
4121 if (auto *I = dyn_cast<Instruction>(this))
4122 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4123 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4124 ShouldInitializeAllMetadata = true;
4125
4126 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004127 print(ROS, MST, IsForDebug);
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004128}
4129
Justin Bognerd7d1a722015-09-27 22:38:50 +00004130void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4131 bool IsForDebug) const {
Dan Gohman12dad632009-08-12 20:56:03 +00004132 formatted_raw_ostream OS(ROS);
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004133 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4134 SlotTracker &SlotTable =
4135 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4136 auto incorporateFunction = [&](const Function *F) {
4137 if (F)
4138 MST.incorporateFunction(*F);
4139 };
4140
Chris Lattner0c19df42008-08-23 22:23:09 +00004141 if (const Instruction *I = dyn_cast<Instruction>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004142 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004143 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004144 W.printInstruction(*I);
Chris Lattner0c19df42008-08-23 22:23:09 +00004145 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004146 incorporateFunction(BB->getParent());
Justin Bognerd7d1a722015-09-27 22:38:50 +00004147 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004148 W.printBasicBlock(BB);
Chris Lattner0c19df42008-08-23 22:23:09 +00004149 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Justin Bognerd7d1a722015-09-27 22:38:50 +00004150 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004151 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4152 W.printGlobal(V);
4153 else if (const Function *F = dyn_cast<Function>(GV))
4154 W.printFunction(F);
4155 else
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004156 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004157 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004158 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
Chris Lattner0c19df42008-08-23 22:23:09 +00004159 } else if (const Constant *C = dyn_cast<Constant>(this)) {
Chris Lattner92c5c122009-02-28 23:20:19 +00004160 TypePrinting TypePrinter;
Chris Lattnere101c442009-02-28 21:26:53 +00004161 TypePrinter.print(C->getType(), OS);
Chris Lattner2ee62d22009-02-28 21:11:05 +00004162 OS << ' ';
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004163 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004164 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004165 this->printAsOperand(OS, /* PrintType */ true, MST);
Chris Lattner0c19df42008-08-23 22:23:09 +00004166 } else {
Nick Lewyckyad1b3d12014-05-09 00:49:03 +00004167 llvm_unreachable("Unknown value to print out!");
Chris Lattner0c19df42008-08-23 22:23:09 +00004168 }
4169}
4170
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004171/// Print without a type, skipping the TypePrinting object.
4172///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004173/// \return \c true iff printing was successful.
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004174static bool printWithoutType(const Value &V, raw_ostream &O,
4175 SlotTracker *Machine, const Module *M) {
4176 if (V.hasName() || isa<GlobalValue>(V) ||
4177 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4178 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4179 return true;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004180 }
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004181 return false;
4182}
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004183
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004184static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4185 ModuleSlotTracker &MST) {
Roman Tereshind96de6f2018-03-22 21:29:07 +00004186 TypePrinting TypePrinter(MST.getModule());
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004187 if (PrintType) {
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004188 TypePrinter.print(V.getType(), O);
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004189 O << ' ';
4190 }
4191
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004192 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4193 MST.getModule());
4194}
4195
4196void Value::printAsOperand(raw_ostream &O, bool PrintType,
4197 const Module *M) const {
4198 if (!M)
4199 M = getModuleFromVal(this);
4200
4201 if (!PrintType)
4202 if (printWithoutType(*this, O, nullptr, M))
4203 return;
4204
4205 SlotTracker Machine(
4206 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4207 ModuleSlotTracker MST(Machine, M);
4208 printAsOperandImpl(*this, O, PrintType, MST);
4209}
4210
4211void Value::printAsOperand(raw_ostream &O, bool PrintType,
4212 ModuleSlotTracker &MST) const {
4213 if (!PrintType)
4214 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4215 return;
4216
4217 printAsOperandImpl(*this, O, PrintType, MST);
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004218}
4219
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004220static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004221 ModuleSlotTracker &MST, const Module *M,
4222 bool OnlyAsOperand) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004223 formatted_raw_ostream OS(ROS);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004224
Roman Tereshind96de6f2018-03-22 21:29:07 +00004225 TypePrinting TypePrinter(M);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004226
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004227 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004228 /* FromValue */ true);
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004229
4230 auto *N = dyn_cast<MDNode>(&MD);
Reid Klecknerb95b4272017-08-30 20:40:36 +00004231 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004232 return;
4233
4234 OS << " = ";
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004235 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004236}
4237
4238void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004239 ModuleSlotTracker MST(M, isa<MDNode>(this));
4240 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4241}
4242
4243void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4244 const Module *M) const {
4245 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004246}
4247
Justin Bognerd7d1a722015-09-27 22:38:50 +00004248void Metadata::print(raw_ostream &OS, const Module *M,
4249 bool /*IsForDebug*/) const {
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004250 ModuleSlotTracker MST(M, isa<MDNode>(this));
4251 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004252}
4253
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004254void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
Justin Bognerd7d1a722015-09-27 22:38:50 +00004255 const Module *M, bool /*IsForDebug*/) const {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004256 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4257}
4258
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00004259void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4260 SlotTracker SlotTable(this);
4261 formatted_raw_ostream OS(ROS);
4262 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4263 W.printModuleSummaryIndex();
4264}
4265
Aaron Ballman615eb472017-10-15 14:32:27 +00004266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerdab942552008-08-25 17:03:15 +00004267// Value::dump - allow easy printing of Values from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004268LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004269void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
Reid Spencer52641832004-05-25 18:14:38 +00004270
Chris Lattnerdab942552008-08-25 17:03:15 +00004271// Type::dump - allow easy printing of Types from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004272LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004273void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
Chris Lattner24025262009-02-28 21:05:51 +00004274
Chris Lattnerdab942552008-08-25 17:03:15 +00004275// Module::dump() - Allow printing of Modules from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004276LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004277void Module::dump() const {
4278 print(dbgs(), nullptr,
4279 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4280}
Bill Wendling3681d112011-12-09 23:18:34 +00004281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004282// Allow printing of Comdats from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004283LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004284void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
David Majnemerdad0a642014-06-27 18:19:56 +00004285
Bill Wendling3681d112011-12-09 23:18:34 +00004286// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004287LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004288void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004289
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004290LLVM_DUMP_METHOD
Duncan P. N. Exon Smitha66dc8f2015-03-15 06:53:32 +00004291void Metadata::dump() const { dump(nullptr); }
4292
4293LLVM_DUMP_METHOD
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004294void Metadata::dump(const Module *M) const {
Justin Bognerd7d1a722015-09-27 22:38:50 +00004295 print(dbgs(), M, /*IsForDebug=*/true);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004296 dbgs() << '\n';
4297}
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00004298
4299// Allow printing of ModuleSummaryIndex from the debugger.
4300LLVM_DUMP_METHOD
4301void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00004302#endif