LLVM API Documentation
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This library implements the functionality defined in llvm/IR/Writer.h 00011 // 00012 // Note that these routines must be extremely tolerant of various errors in the 00013 // LLVM code, because it can be used for debugging transformations. 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "AsmWriter.h" 00018 #include "llvm/ADT/DenseMap.h" 00019 #include "llvm/ADT/STLExtras.h" 00020 #include "llvm/ADT/SmallString.h" 00021 #include "llvm/ADT/StringExtras.h" 00022 #include "llvm/IR/AssemblyAnnotationWriter.h" 00023 #include "llvm/IR/CFG.h" 00024 #include "llvm/IR/CallingConv.h" 00025 #include "llvm/IR/Constants.h" 00026 #include "llvm/IR/DebugInfo.h" 00027 #include "llvm/IR/DerivedTypes.h" 00028 #include "llvm/IR/IRPrintingPasses.h" 00029 #include "llvm/IR/InlineAsm.h" 00030 #include "llvm/IR/IntrinsicInst.h" 00031 #include "llvm/IR/LLVMContext.h" 00032 #include "llvm/IR/Module.h" 00033 #include "llvm/IR/Operator.h" 00034 #include "llvm/IR/TypeFinder.h" 00035 #include "llvm/IR/ValueSymbolTable.h" 00036 #include "llvm/Support/Debug.h" 00037 #include "llvm/Support/Dwarf.h" 00038 #include "llvm/Support/ErrorHandling.h" 00039 #include "llvm/Support/FormattedStream.h" 00040 #include "llvm/Support/MathExtras.h" 00041 #include <algorithm> 00042 #include <cctype> 00043 using namespace llvm; 00044 00045 // Make virtual table appear in this compilation unit. 00046 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 00047 00048 //===----------------------------------------------------------------------===// 00049 // Helper Functions 00050 //===----------------------------------------------------------------------===// 00051 00052 namespace { 00053 struct OrderMap { 00054 DenseMap<const Value *, std::pair<unsigned, bool>> IDs; 00055 00056 unsigned size() const { return IDs.size(); } 00057 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; } 00058 std::pair<unsigned, bool> lookup(const Value *V) const { 00059 return IDs.lookup(V); 00060 } 00061 void index(const Value *V) { 00062 // Explicitly sequence get-size and insert-value operations to avoid UB. 00063 unsigned ID = IDs.size() + 1; 00064 IDs[V].first = ID; 00065 } 00066 }; 00067 } 00068 00069 static void orderValue(const Value *V, OrderMap &OM) { 00070 if (OM.lookup(V).first) 00071 return; 00072 00073 if (const Constant *C = dyn_cast<Constant>(V)) 00074 if (C->getNumOperands() && !isa<GlobalValue>(C)) 00075 for (const Value *Op : C->operands()) 00076 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) 00077 orderValue(Op, OM); 00078 00079 // Note: we cannot cache this lookup above, since inserting into the map 00080 // changes the map's size, and thus affects the other IDs. 00081 OM.index(V); 00082 } 00083 00084 static OrderMap orderModule(const Module *M) { 00085 // This needs to match the order used by ValueEnumerator::ValueEnumerator() 00086 // and ValueEnumerator::incorporateFunction(). 00087 OrderMap OM; 00088 00089 for (const GlobalVariable &G : M->globals()) { 00090 if (G.hasInitializer()) 00091 if (!isa<GlobalValue>(G.getInitializer())) 00092 orderValue(G.getInitializer(), OM); 00093 orderValue(&G, OM); 00094 } 00095 for (const GlobalAlias &A : M->aliases()) { 00096 if (!isa<GlobalValue>(A.getAliasee())) 00097 orderValue(A.getAliasee(), OM); 00098 orderValue(&A, OM); 00099 } 00100 for (const Function &F : *M) { 00101 if (F.hasPrefixData()) 00102 if (!isa<GlobalValue>(F.getPrefixData())) 00103 orderValue(F.getPrefixData(), OM); 00104 orderValue(&F, OM); 00105 00106 if (F.isDeclaration()) 00107 continue; 00108 00109 for (const Argument &A : F.args()) 00110 orderValue(&A, OM); 00111 for (const BasicBlock &BB : F) { 00112 orderValue(&BB, OM); 00113 for (const Instruction &I : BB) { 00114 for (const Value *Op : I.operands()) 00115 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || 00116 isa<InlineAsm>(*Op)) 00117 orderValue(Op, OM); 00118 orderValue(&I, OM); 00119 } 00120 } 00121 } 00122 return OM; 00123 } 00124 00125 static void predictValueUseListOrderImpl(const Value *V, const Function *F, 00126 unsigned ID, const OrderMap &OM, 00127 UseListOrderStack &Stack) { 00128 // Predict use-list order for this one. 00129 typedef std::pair<const Use *, unsigned> Entry; 00130 SmallVector<Entry, 64> List; 00131 for (const Use &U : V->uses()) 00132 // Check if this user will be serialized. 00133 if (OM.lookup(U.getUser()).first) 00134 List.push_back(std::make_pair(&U, List.size())); 00135 00136 if (List.size() < 2) 00137 // We may have lost some users. 00138 return; 00139 00140 bool GetsReversed = 00141 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V); 00142 if (auto *BA = dyn_cast<BlockAddress>(V)) 00143 ID = OM.lookup(BA->getBasicBlock()).first; 00144 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) { 00145 const Use *LU = L.first; 00146 const Use *RU = R.first; 00147 if (LU == RU) 00148 return false; 00149 00150 auto LID = OM.lookup(LU->getUser()).first; 00151 auto RID = OM.lookup(RU->getUser()).first; 00152 00153 // If ID is 4, then expect: 7 6 5 1 2 3. 00154 if (LID < RID) { 00155 if (GetsReversed) 00156 if (RID <= ID) 00157 return true; 00158 return false; 00159 } 00160 if (RID < LID) { 00161 if (GetsReversed) 00162 if (LID <= ID) 00163 return false; 00164 return true; 00165 } 00166 00167 // LID and RID are equal, so we have different operands of the same user. 00168 // Assume operands are added in order for all instructions. 00169 if (GetsReversed) 00170 if (LID <= ID) 00171 return LU->getOperandNo() < RU->getOperandNo(); 00172 return LU->getOperandNo() > RU->getOperandNo(); 00173 }); 00174 00175 if (std::is_sorted( 00176 List.begin(), List.end(), 00177 [](const Entry &L, const Entry &R) { return L.second < R.second; })) 00178 // Order is already correct. 00179 return; 00180 00181 // Store the shuffle. 00182 Stack.emplace_back(V, F, List.size()); 00183 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size"); 00184 for (size_t I = 0, E = List.size(); I != E; ++I) 00185 Stack.back().Shuffle[I] = List[I].second; 00186 } 00187 00188 static void predictValueUseListOrder(const Value *V, const Function *F, 00189 OrderMap &OM, UseListOrderStack &Stack) { 00190 auto &IDPair = OM[V]; 00191 assert(IDPair.first && "Unmapped value"); 00192 if (IDPair.second) 00193 // Already predicted. 00194 return; 00195 00196 // Do the actual prediction. 00197 IDPair.second = true; 00198 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end()) 00199 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack); 00200 00201 // Recursive descent into constants. 00202 if (const Constant *C = dyn_cast<Constant>(V)) 00203 if (C->getNumOperands()) // Visit GlobalValues. 00204 for (const Value *Op : C->operands()) 00205 if (isa<Constant>(Op)) // Visit GlobalValues. 00206 predictValueUseListOrder(Op, F, OM, Stack); 00207 } 00208 00209 static UseListOrderStack predictUseListOrder(const Module *M) { 00210 OrderMap OM = orderModule(M); 00211 00212 // Use-list orders need to be serialized after all the users have been added 00213 // to a value, or else the shuffles will be incomplete. Store them per 00214 // function in a stack. 00215 // 00216 // Aside from function order, the order of values doesn't matter much here. 00217 UseListOrderStack Stack; 00218 00219 // We want to visit the functions backward now so we can list function-local 00220 // constants in the last Function they're used in. Module-level constants 00221 // have already been visited above. 00222 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) { 00223 const Function &F = *I; 00224 if (F.isDeclaration()) 00225 continue; 00226 for (const BasicBlock &BB : F) 00227 predictValueUseListOrder(&BB, &F, OM, Stack); 00228 for (const Argument &A : F.args()) 00229 predictValueUseListOrder(&A, &F, OM, Stack); 00230 for (const BasicBlock &BB : F) 00231 for (const Instruction &I : BB) 00232 for (const Value *Op : I.operands()) 00233 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues. 00234 predictValueUseListOrder(Op, &F, OM, Stack); 00235 for (const BasicBlock &BB : F) 00236 for (const Instruction &I : BB) 00237 predictValueUseListOrder(&I, &F, OM, Stack); 00238 } 00239 00240 // Visit globals last. 00241 for (const GlobalVariable &G : M->globals()) 00242 predictValueUseListOrder(&G, nullptr, OM, Stack); 00243 for (const Function &F : *M) 00244 predictValueUseListOrder(&F, nullptr, OM, Stack); 00245 for (const GlobalAlias &A : M->aliases()) 00246 predictValueUseListOrder(&A, nullptr, OM, Stack); 00247 for (const GlobalVariable &G : M->globals()) 00248 if (G.hasInitializer()) 00249 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack); 00250 for (const GlobalAlias &A : M->aliases()) 00251 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack); 00252 for (const Function &F : *M) 00253 if (F.hasPrefixData()) 00254 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack); 00255 00256 return Stack; 00257 } 00258 00259 static const Module *getModuleFromVal(const Value *V) { 00260 if (const Argument *MA = dyn_cast<Argument>(V)) 00261 return MA->getParent() ? MA->getParent()->getParent() : nullptr; 00262 00263 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 00264 return BB->getParent() ? BB->getParent()->getParent() : nullptr; 00265 00266 if (const Instruction *I = dyn_cast<Instruction>(V)) { 00267 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr; 00268 return M ? M->getParent() : nullptr; 00269 } 00270 00271 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00272 return GV->getParent(); 00273 return nullptr; 00274 } 00275 00276 static void PrintCallingConv(unsigned cc, raw_ostream &Out) { 00277 switch (cc) { 00278 default: Out << "cc" << cc; break; 00279 case CallingConv::Fast: Out << "fastcc"; break; 00280 case CallingConv::Cold: Out << "coldcc"; break; 00281 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break; 00282 case CallingConv::AnyReg: Out << "anyregcc"; break; 00283 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break; 00284 case CallingConv::PreserveAll: Out << "preserve_allcc"; break; 00285 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break; 00286 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break; 00287 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break; 00288 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break; 00289 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break; 00290 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break; 00291 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break; 00292 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break; 00293 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break; 00294 case CallingConv::PTX_Device: Out << "ptx_device"; break; 00295 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break; 00296 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break; 00297 case CallingConv::SPIR_FUNC: Out << "spir_func"; break; 00298 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break; 00299 } 00300 } 00301 00302 // PrintEscapedString - Print each character of the specified string, escaping 00303 // it if it is not printable or if it is an escape char. 00304 static void PrintEscapedString(StringRef Name, raw_ostream &Out) { 00305 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 00306 unsigned char C = Name[i]; 00307 if (isprint(C) && C != '\\' && C != '"') 00308 Out << C; 00309 else 00310 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 00311 } 00312 } 00313 00314 enum PrefixType { 00315 GlobalPrefix, 00316 ComdatPrefix, 00317 LabelPrefix, 00318 LocalPrefix, 00319 NoPrefix 00320 }; 00321 00322 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 00323 /// prefixed with % (if the string only contains simple characters) or is 00324 /// surrounded with ""'s (if it has special chars in it). Print it out. 00325 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) { 00326 assert(!Name.empty() && "Cannot get empty name!"); 00327 switch (Prefix) { 00328 case NoPrefix: break; 00329 case GlobalPrefix: OS << '@'; break; 00330 case ComdatPrefix: OS << '$'; break; 00331 case LabelPrefix: break; 00332 case LocalPrefix: OS << '%'; break; 00333 } 00334 00335 // Scan the name to see if it needs quotes first. 00336 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0])); 00337 if (!NeedsQuotes) { 00338 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 00339 // By making this unsigned, the value passed in to isalnum will always be 00340 // in the range 0-255. This is important when building with MSVC because 00341 // its implementation will assert. This situation can arise when dealing 00342 // with UTF-8 multibyte characters. 00343 unsigned char C = Name[i]; 00344 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' && 00345 C != '_') { 00346 NeedsQuotes = true; 00347 break; 00348 } 00349 } 00350 } 00351 00352 // If we didn't need any quotes, just write out the name in one blast. 00353 if (!NeedsQuotes) { 00354 OS << Name; 00355 return; 00356 } 00357 00358 // Okay, we need quotes. Output the quotes and escape any scary characters as 00359 // needed. 00360 OS << '"'; 00361 PrintEscapedString(Name, OS); 00362 OS << '"'; 00363 } 00364 00365 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 00366 /// prefixed with % (if the string only contains simple characters) or is 00367 /// surrounded with ""'s (if it has special chars in it). Print it out. 00368 static void PrintLLVMName(raw_ostream &OS, const Value *V) { 00369 PrintLLVMName(OS, V->getName(), 00370 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 00371 } 00372 00373 00374 namespace llvm { 00375 00376 void TypePrinting::incorporateTypes(const Module &M) { 00377 NamedTypes.run(M, false); 00378 00379 // The list of struct types we got back includes all the struct types, split 00380 // the unnamed ones out to a numbering and remove the anonymous structs. 00381 unsigned NextNumber = 0; 00382 00383 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E; 00384 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) { 00385 StructType *STy = *I; 00386 00387 // Ignore anonymous types. 00388 if (STy->isLiteral()) 00389 continue; 00390 00391 if (STy->getName().empty()) 00392 NumberedTypes[STy] = NextNumber++; 00393 else 00394 *NextToUse++ = STy; 00395 } 00396 00397 NamedTypes.erase(NextToUse, NamedTypes.end()); 00398 } 00399 00400 00401 /// CalcTypeName - Write the specified type to the specified raw_ostream, making 00402 /// use of type names or up references to shorten the type name where possible. 00403 void TypePrinting::print(Type *Ty, raw_ostream &OS) { 00404 switch (Ty->getTypeID()) { 00405 case Type::VoidTyID: OS << "void"; return; 00406 case Type::HalfTyID: OS << "half"; return; 00407 case Type::FloatTyID: OS << "float"; return; 00408 case Type::DoubleTyID: OS << "double"; return; 00409 case Type::X86_FP80TyID: OS << "x86_fp80"; return; 00410 case Type::FP128TyID: OS << "fp128"; return; 00411 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return; 00412 case Type::LabelTyID: OS << "label"; return; 00413 case Type::MetadataTyID: OS << "metadata"; return; 00414 case Type::X86_MMXTyID: OS << "x86_mmx"; return; 00415 case Type::IntegerTyID: 00416 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 00417 return; 00418 00419 case Type::FunctionTyID: { 00420 FunctionType *FTy = cast<FunctionType>(Ty); 00421 print(FTy->getReturnType(), OS); 00422 OS << " ("; 00423 for (FunctionType::param_iterator I = FTy->param_begin(), 00424 E = FTy->param_end(); I != E; ++I) { 00425 if (I != FTy->param_begin()) 00426 OS << ", "; 00427 print(*I, OS); 00428 } 00429 if (FTy->isVarArg()) { 00430 if (FTy->getNumParams()) OS << ", "; 00431 OS << "..."; 00432 } 00433 OS << ')'; 00434 return; 00435 } 00436 case Type::StructTyID: { 00437 StructType *STy = cast<StructType>(Ty); 00438 00439 if (STy->isLiteral()) 00440 return printStructBody(STy, OS); 00441 00442 if (!STy->getName().empty()) 00443 return PrintLLVMName(OS, STy->getName(), LocalPrefix); 00444 00445 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy); 00446 if (I != NumberedTypes.end()) 00447 OS << '%' << I->second; 00448 else // Not enumerated, print the hex address. 00449 OS << "%\"type " << STy << '\"'; 00450 return; 00451 } 00452 case Type::PointerTyID: { 00453 PointerType *PTy = cast<PointerType>(Ty); 00454 print(PTy->getElementType(), OS); 00455 if (unsigned AddressSpace = PTy->getAddressSpace()) 00456 OS << " addrspace(" << AddressSpace << ')'; 00457 OS << '*'; 00458 return; 00459 } 00460 case Type::ArrayTyID: { 00461 ArrayType *ATy = cast<ArrayType>(Ty); 00462 OS << '[' << ATy->getNumElements() << " x "; 00463 print(ATy->getElementType(), OS); 00464 OS << ']'; 00465 return; 00466 } 00467 case Type::VectorTyID: { 00468 VectorType *PTy = cast<VectorType>(Ty); 00469 OS << "<" << PTy->getNumElements() << " x "; 00470 print(PTy->getElementType(), OS); 00471 OS << '>'; 00472 return; 00473 } 00474 } 00475 llvm_unreachable("Invalid TypeID"); 00476 } 00477 00478 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) { 00479 if (STy->isOpaque()) { 00480 OS << "opaque"; 00481 return; 00482 } 00483 00484 if (STy->isPacked()) 00485 OS << '<'; 00486 00487 if (STy->getNumElements() == 0) { 00488 OS << "{}"; 00489 } else { 00490 StructType::element_iterator I = STy->element_begin(); 00491 OS << "{ "; 00492 print(*I++, OS); 00493 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) { 00494 OS << ", "; 00495 print(*I, OS); 00496 } 00497 00498 OS << " }"; 00499 } 00500 if (STy->isPacked()) 00501 OS << '>'; 00502 } 00503 00504 //===----------------------------------------------------------------------===// 00505 // SlotTracker Class: Enumerate slot numbers for unnamed values 00506 //===----------------------------------------------------------------------===// 00507 /// This class provides computation of slot numbers for LLVM Assembly writing. 00508 /// 00509 class SlotTracker { 00510 public: 00511 /// ValueMap - A mapping of Values to slot numbers. 00512 typedef DenseMap<const Value*, unsigned> ValueMap; 00513 00514 private: 00515 /// TheModule - The module for which we are holding slot numbers. 00516 const Module* TheModule; 00517 00518 /// TheFunction - The function for which we are holding slot numbers. 00519 const Function* TheFunction; 00520 bool FunctionProcessed; 00521 00522 /// mMap - The slot map for the module level data. 00523 ValueMap mMap; 00524 unsigned mNext; 00525 00526 /// fMap - The slot map for the function level data. 00527 ValueMap fMap; 00528 unsigned fNext; 00529 00530 /// mdnMap - Map for MDNodes. 00531 DenseMap<const MDNode*, unsigned> mdnMap; 00532 unsigned mdnNext; 00533 00534 /// asMap - The slot map for attribute sets. 00535 DenseMap<AttributeSet, unsigned> asMap; 00536 unsigned asNext; 00537 public: 00538 /// Construct from a module 00539 explicit SlotTracker(const Module *M); 00540 /// Construct from a function, starting out in incorp state. 00541 explicit SlotTracker(const Function *F); 00542 00543 /// Return the slot number of the specified value in it's type 00544 /// plane. If something is not in the SlotTracker, return -1. 00545 int getLocalSlot(const Value *V); 00546 int getGlobalSlot(const GlobalValue *V); 00547 int getMetadataSlot(const MDNode *N); 00548 int getAttributeGroupSlot(AttributeSet AS); 00549 00550 /// If you'd like to deal with a function instead of just a module, use 00551 /// this method to get its data into the SlotTracker. 00552 void incorporateFunction(const Function *F) { 00553 TheFunction = F; 00554 FunctionProcessed = false; 00555 } 00556 00557 const Function *getFunction() const { return TheFunction; } 00558 00559 /// After calling incorporateFunction, use this method to remove the 00560 /// most recently incorporated function from the SlotTracker. This 00561 /// will reset the state of the machine back to just the module contents. 00562 void purgeFunction(); 00563 00564 /// MDNode map iterators. 00565 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator; 00566 mdn_iterator mdn_begin() { return mdnMap.begin(); } 00567 mdn_iterator mdn_end() { return mdnMap.end(); } 00568 unsigned mdn_size() const { return mdnMap.size(); } 00569 bool mdn_empty() const { return mdnMap.empty(); } 00570 00571 /// AttributeSet map iterators. 00572 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator; 00573 as_iterator as_begin() { return asMap.begin(); } 00574 as_iterator as_end() { return asMap.end(); } 00575 unsigned as_size() const { return asMap.size(); } 00576 bool as_empty() const { return asMap.empty(); } 00577 00578 /// This function does the actual initialization. 00579 inline void initialize(); 00580 00581 // Implementation Details 00582 private: 00583 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 00584 void CreateModuleSlot(const GlobalValue *V); 00585 00586 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 00587 void CreateMetadataSlot(const MDNode *N); 00588 00589 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 00590 void CreateFunctionSlot(const Value *V); 00591 00592 /// \brief Insert the specified AttributeSet into the slot table. 00593 void CreateAttributeSetSlot(AttributeSet AS); 00594 00595 /// Add all of the module level global variables (and their initializers) 00596 /// and function declarations, but not the contents of those functions. 00597 void processModule(); 00598 00599 /// Add all of the functions arguments, basic blocks, and instructions. 00600 void processFunction(); 00601 00602 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION; 00603 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION; 00604 }; 00605 00606 SlotTracker *createSlotTracker(const Module *M) { 00607 return new SlotTracker(M); 00608 } 00609 00610 static SlotTracker *createSlotTracker(const Value *V) { 00611 if (const Argument *FA = dyn_cast<Argument>(V)) 00612 return new SlotTracker(FA->getParent()); 00613 00614 if (const Instruction *I = dyn_cast<Instruction>(V)) 00615 if (I->getParent()) 00616 return new SlotTracker(I->getParent()->getParent()); 00617 00618 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 00619 return new SlotTracker(BB->getParent()); 00620 00621 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 00622 return new SlotTracker(GV->getParent()); 00623 00624 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 00625 return new SlotTracker(GA->getParent()); 00626 00627 if (const Function *Func = dyn_cast<Function>(V)) 00628 return new SlotTracker(Func); 00629 00630 if (const MDNode *MD = dyn_cast<MDNode>(V)) { 00631 if (!MD->isFunctionLocal()) 00632 return new SlotTracker(MD->getFunction()); 00633 00634 return new SlotTracker((Function *)nullptr); 00635 } 00636 00637 return nullptr; 00638 } 00639 00640 #if 0 00641 #define ST_DEBUG(X) dbgs() << X 00642 #else 00643 #define ST_DEBUG(X) 00644 #endif 00645 00646 // Module level constructor. Causes the contents of the Module (sans functions) 00647 // to be added to the slot table. 00648 SlotTracker::SlotTracker(const Module *M) 00649 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false), 00650 mNext(0), fNext(0), mdnNext(0), asNext(0) { 00651 } 00652 00653 // Function level constructor. Causes the contents of the Module and the one 00654 // function provided to be added to the slot table. 00655 SlotTracker::SlotTracker(const Function *F) 00656 : TheModule(F ? F->getParent() : nullptr), TheFunction(F), 00657 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) { 00658 } 00659 00660 inline void SlotTracker::initialize() { 00661 if (TheModule) { 00662 processModule(); 00663 TheModule = nullptr; ///< Prevent re-processing next time we're called. 00664 } 00665 00666 if (TheFunction && !FunctionProcessed) 00667 processFunction(); 00668 } 00669 00670 // Iterate through all the global variables, functions, and global 00671 // variable initializers and create slots for them. 00672 void SlotTracker::processModule() { 00673 ST_DEBUG("begin processModule!\n"); 00674 00675 // Add all of the unnamed global variables to the value table. 00676 for (Module::const_global_iterator I = TheModule->global_begin(), 00677 E = TheModule->global_end(); I != E; ++I) { 00678 if (!I->hasName()) 00679 CreateModuleSlot(I); 00680 } 00681 00682 // Add metadata used by named metadata. 00683 for (Module::const_named_metadata_iterator 00684 I = TheModule->named_metadata_begin(), 00685 E = TheModule->named_metadata_end(); I != E; ++I) { 00686 const NamedMDNode *NMD = I; 00687 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 00688 CreateMetadataSlot(NMD->getOperand(i)); 00689 } 00690 00691 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 00692 I != E; ++I) { 00693 if (!I->hasName()) 00694 // Add all the unnamed functions to the table. 00695 CreateModuleSlot(I); 00696 00697 // Add all the function attributes to the table. 00698 // FIXME: Add attributes of other objects? 00699 AttributeSet FnAttrs = I->getAttributes().getFnAttributes(); 00700 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex)) 00701 CreateAttributeSetSlot(FnAttrs); 00702 } 00703 00704 ST_DEBUG("end processModule!\n"); 00705 } 00706 00707 // Process the arguments, basic blocks, and instructions of a function. 00708 void SlotTracker::processFunction() { 00709 ST_DEBUG("begin processFunction!\n"); 00710 fNext = 0; 00711 00712 // Add all the function arguments with no names. 00713 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 00714 AE = TheFunction->arg_end(); AI != AE; ++AI) 00715 if (!AI->hasName()) 00716 CreateFunctionSlot(AI); 00717 00718 ST_DEBUG("Inserting Instructions:\n"); 00719 00720 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst; 00721 00722 // Add all of the basic blocks and instructions with no names. 00723 for (Function::const_iterator BB = TheFunction->begin(), 00724 E = TheFunction->end(); BB != E; ++BB) { 00725 if (!BB->hasName()) 00726 CreateFunctionSlot(BB); 00727 00728 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 00729 ++I) { 00730 if (!I->getType()->isVoidTy() && !I->hasName()) 00731 CreateFunctionSlot(I); 00732 00733 // Intrinsics can directly use metadata. We allow direct calls to any 00734 // llvm.foo function here, because the target may not be linked into the 00735 // optimizer. 00736 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 00737 if (Function *F = CI->getCalledFunction()) 00738 if (F->isIntrinsic()) 00739 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00740 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i))) 00741 CreateMetadataSlot(N); 00742 00743 // Add all the call attributes to the table. 00744 AttributeSet Attrs = CI->getAttributes().getFnAttributes(); 00745 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 00746 CreateAttributeSetSlot(Attrs); 00747 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) { 00748 // Add all the call attributes to the table. 00749 AttributeSet Attrs = II->getAttributes().getFnAttributes(); 00750 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 00751 CreateAttributeSetSlot(Attrs); 00752 } 00753 00754 // Process metadata attached with this instruction. 00755 I->getAllMetadata(MDForInst); 00756 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i) 00757 CreateMetadataSlot(MDForInst[i].second); 00758 MDForInst.clear(); 00759 } 00760 } 00761 00762 FunctionProcessed = true; 00763 00764 ST_DEBUG("end processFunction!\n"); 00765 } 00766 00767 /// Clean up after incorporating a function. This is the only way to get out of 00768 /// the function incorporation state that affects get*Slot/Create*Slot. Function 00769 /// incorporation state is indicated by TheFunction != 0. 00770 void SlotTracker::purgeFunction() { 00771 ST_DEBUG("begin purgeFunction!\n"); 00772 fMap.clear(); // Simply discard the function level map 00773 TheFunction = nullptr; 00774 FunctionProcessed = false; 00775 ST_DEBUG("end purgeFunction!\n"); 00776 } 00777 00778 /// getGlobalSlot - Get the slot number of a global value. 00779 int SlotTracker::getGlobalSlot(const GlobalValue *V) { 00780 // Check for uninitialized state and do lazy initialization. 00781 initialize(); 00782 00783 // Find the value in the module map 00784 ValueMap::iterator MI = mMap.find(V); 00785 return MI == mMap.end() ? -1 : (int)MI->second; 00786 } 00787 00788 /// getMetadataSlot - Get the slot number of a MDNode. 00789 int SlotTracker::getMetadataSlot(const MDNode *N) { 00790 // Check for uninitialized state and do lazy initialization. 00791 initialize(); 00792 00793 // Find the MDNode in the module map 00794 mdn_iterator MI = mdnMap.find(N); 00795 return MI == mdnMap.end() ? -1 : (int)MI->second; 00796 } 00797 00798 00799 /// getLocalSlot - Get the slot number for a value that is local to a function. 00800 int SlotTracker::getLocalSlot(const Value *V) { 00801 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 00802 00803 // Check for uninitialized state and do lazy initialization. 00804 initialize(); 00805 00806 ValueMap::iterator FI = fMap.find(V); 00807 return FI == fMap.end() ? -1 : (int)FI->second; 00808 } 00809 00810 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) { 00811 // Check for uninitialized state and do lazy initialization. 00812 initialize(); 00813 00814 // Find the AttributeSet in the module map. 00815 as_iterator AI = asMap.find(AS); 00816 return AI == asMap.end() ? -1 : (int)AI->second; 00817 } 00818 00819 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 00820 void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 00821 assert(V && "Can't insert a null Value into SlotTracker!"); 00822 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 00823 assert(!V->hasName() && "Doesn't need a slot!"); 00824 00825 unsigned DestSlot = mNext++; 00826 mMap[V] = DestSlot; 00827 00828 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 00829 DestSlot << " ["); 00830 // G = Global, F = Function, A = Alias, o = other 00831 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 00832 (isa<Function>(V) ? 'F' : 00833 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 00834 } 00835 00836 /// CreateSlot - Create a new slot for the specified value if it has no name. 00837 void SlotTracker::CreateFunctionSlot(const Value *V) { 00838 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 00839 00840 unsigned DestSlot = fNext++; 00841 fMap[V] = DestSlot; 00842 00843 // G = Global, F = Function, o = other 00844 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 00845 DestSlot << " [o]\n"); 00846 } 00847 00848 /// CreateModuleSlot - Insert the specified MDNode* into the slot table. 00849 void SlotTracker::CreateMetadataSlot(const MDNode *N) { 00850 assert(N && "Can't insert a null Value into SlotTracker!"); 00851 00852 // Don't insert if N is a function-local metadata, these are always printed 00853 // inline. 00854 if (!N->isFunctionLocal()) { 00855 mdn_iterator I = mdnMap.find(N); 00856 if (I != mdnMap.end()) 00857 return; 00858 00859 unsigned DestSlot = mdnNext++; 00860 mdnMap[N] = DestSlot; 00861 } 00862 00863 // Recursively add any MDNodes referenced by operands. 00864 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 00865 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 00866 CreateMetadataSlot(Op); 00867 } 00868 00869 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) { 00870 assert(AS.hasAttributes(AttributeSet::FunctionIndex) && 00871 "Doesn't need a slot!"); 00872 00873 as_iterator I = asMap.find(AS); 00874 if (I != asMap.end()) 00875 return; 00876 00877 unsigned DestSlot = asNext++; 00878 asMap[AS] = DestSlot; 00879 } 00880 00881 //===----------------------------------------------------------------------===// 00882 // AsmWriter Implementation 00883 //===----------------------------------------------------------------------===// 00884 00885 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 00886 TypePrinting *TypePrinter, 00887 SlotTracker *Machine, 00888 const Module *Context); 00889 00890 static const char *getPredicateText(unsigned predicate) { 00891 const char * pred = "unknown"; 00892 switch (predicate) { 00893 case FCmpInst::FCMP_FALSE: pred = "false"; break; 00894 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 00895 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 00896 case FCmpInst::FCMP_OGE: pred = "oge"; break; 00897 case FCmpInst::FCMP_OLT: pred = "olt"; break; 00898 case FCmpInst::FCMP_OLE: pred = "ole"; break; 00899 case FCmpInst::FCMP_ONE: pred = "one"; break; 00900 case FCmpInst::FCMP_ORD: pred = "ord"; break; 00901 case FCmpInst::FCMP_UNO: pred = "uno"; break; 00902 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 00903 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 00904 case FCmpInst::FCMP_UGE: pred = "uge"; break; 00905 case FCmpInst::FCMP_ULT: pred = "ult"; break; 00906 case FCmpInst::FCMP_ULE: pred = "ule"; break; 00907 case FCmpInst::FCMP_UNE: pred = "une"; break; 00908 case FCmpInst::FCMP_TRUE: pred = "true"; break; 00909 case ICmpInst::ICMP_EQ: pred = "eq"; break; 00910 case ICmpInst::ICMP_NE: pred = "ne"; break; 00911 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 00912 case ICmpInst::ICMP_SGE: pred = "sge"; break; 00913 case ICmpInst::ICMP_SLT: pred = "slt"; break; 00914 case ICmpInst::ICMP_SLE: pred = "sle"; break; 00915 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 00916 case ICmpInst::ICMP_UGE: pred = "uge"; break; 00917 case ICmpInst::ICMP_ULT: pred = "ult"; break; 00918 case ICmpInst::ICMP_ULE: pred = "ule"; break; 00919 } 00920 return pred; 00921 } 00922 00923 static void writeAtomicRMWOperation(raw_ostream &Out, 00924 AtomicRMWInst::BinOp Op) { 00925 switch (Op) { 00926 default: Out << " <unknown operation " << Op << ">"; break; 00927 case AtomicRMWInst::Xchg: Out << " xchg"; break; 00928 case AtomicRMWInst::Add: Out << " add"; break; 00929 case AtomicRMWInst::Sub: Out << " sub"; break; 00930 case AtomicRMWInst::And: Out << " and"; break; 00931 case AtomicRMWInst::Nand: Out << " nand"; break; 00932 case AtomicRMWInst::Or: Out << " or"; break; 00933 case AtomicRMWInst::Xor: Out << " xor"; break; 00934 case AtomicRMWInst::Max: Out << " max"; break; 00935 case AtomicRMWInst::Min: Out << " min"; break; 00936 case AtomicRMWInst::UMax: Out << " umax"; break; 00937 case AtomicRMWInst::UMin: Out << " umin"; break; 00938 } 00939 } 00940 00941 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 00942 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) { 00943 // Unsafe algebra implies all the others, no need to write them all out 00944 if (FPO->hasUnsafeAlgebra()) 00945 Out << " fast"; 00946 else { 00947 if (FPO->hasNoNaNs()) 00948 Out << " nnan"; 00949 if (FPO->hasNoInfs()) 00950 Out << " ninf"; 00951 if (FPO->hasNoSignedZeros()) 00952 Out << " nsz"; 00953 if (FPO->hasAllowReciprocal()) 00954 Out << " arcp"; 00955 } 00956 } 00957 00958 if (const OverflowingBinaryOperator *OBO = 00959 dyn_cast<OverflowingBinaryOperator>(U)) { 00960 if (OBO->hasNoUnsignedWrap()) 00961 Out << " nuw"; 00962 if (OBO->hasNoSignedWrap()) 00963 Out << " nsw"; 00964 } else if (const PossiblyExactOperator *Div = 00965 dyn_cast<PossiblyExactOperator>(U)) { 00966 if (Div->isExact()) 00967 Out << " exact"; 00968 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 00969 if (GEP->isInBounds()) 00970 Out << " inbounds"; 00971 } 00972 } 00973 00974 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 00975 TypePrinting &TypePrinter, 00976 SlotTracker *Machine, 00977 const Module *Context) { 00978 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 00979 if (CI->getType()->isIntegerTy(1)) { 00980 Out << (CI->getZExtValue() ? "true" : "false"); 00981 return; 00982 } 00983 Out << CI->getValue(); 00984 return; 00985 } 00986 00987 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 00988 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle || 00989 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) { 00990 // We would like to output the FP constant value in exponential notation, 00991 // but we cannot do this if doing so will lose precision. Check here to 00992 // make sure that we only output it in exponential format if we can parse 00993 // the value back and get the same value. 00994 // 00995 bool ignored; 00996 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf; 00997 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 00998 bool isInf = CFP->getValueAPF().isInfinity(); 00999 bool isNaN = CFP->getValueAPF().isNaN(); 01000 if (!isHalf && !isInf && !isNaN) { 01001 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 01002 CFP->getValueAPF().convertToFloat(); 01003 SmallString<128> StrVal; 01004 raw_svector_ostream(StrVal) << Val; 01005 01006 // Check to make sure that the stringized number is not some string like 01007 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 01008 // that the string matches the "[-+]?[0-9]" regex. 01009 // 01010 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 01011 ((StrVal[0] == '-' || StrVal[0] == '+') && 01012 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 01013 // Reparse stringized version! 01014 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) { 01015 Out << StrVal.str(); 01016 return; 01017 } 01018 } 01019 } 01020 // Otherwise we could not reparse it to exactly the same value, so we must 01021 // output the string in hexadecimal format! Note that loading and storing 01022 // floating point types changes the bits of NaNs on some hosts, notably 01023 // x86, so we must not use these types. 01024 static_assert(sizeof(double) == sizeof(uint64_t), 01025 "assuming that double is 64 bits!"); 01026 char Buffer[40]; 01027 APFloat apf = CFP->getValueAPF(); 01028 // Halves and floats are represented in ASCII IR as double, convert. 01029 if (!isDouble) 01030 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 01031 &ignored); 01032 Out << "0x" << 01033 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 01034 Buffer+40); 01035 return; 01036 } 01037 01038 // Either half, or some form of long double. 01039 // These appear as a magic letter identifying the type, then a 01040 // fixed number of hex digits. 01041 Out << "0x"; 01042 // Bit position, in the current word, of the next nibble to print. 01043 int shiftcount; 01044 01045 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) { 01046 Out << 'K'; 01047 // api needed to prevent premature destruction 01048 APInt api = CFP->getValueAPF().bitcastToAPInt(); 01049 const uint64_t* p = api.getRawData(); 01050 uint64_t word = p[1]; 01051 shiftcount = 12; 01052 int width = api.getBitWidth(); 01053 for (int j=0; j<width; j+=4, shiftcount-=4) { 01054 unsigned int nibble = (word>>shiftcount) & 15; 01055 if (nibble < 10) 01056 Out << (unsigned char)(nibble + '0'); 01057 else 01058 Out << (unsigned char)(nibble - 10 + 'A'); 01059 if (shiftcount == 0 && j+4 < width) { 01060 word = *p; 01061 shiftcount = 64; 01062 if (width-j-4 < 64) 01063 shiftcount = width-j-4; 01064 } 01065 } 01066 return; 01067 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) { 01068 shiftcount = 60; 01069 Out << 'L'; 01070 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) { 01071 shiftcount = 60; 01072 Out << 'M'; 01073 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) { 01074 shiftcount = 12; 01075 Out << 'H'; 01076 } else 01077 llvm_unreachable("Unsupported floating point type"); 01078 // api needed to prevent premature destruction 01079 APInt api = CFP->getValueAPF().bitcastToAPInt(); 01080 const uint64_t* p = api.getRawData(); 01081 uint64_t word = *p; 01082 int width = api.getBitWidth(); 01083 for (int j=0; j<width; j+=4, shiftcount-=4) { 01084 unsigned int nibble = (word>>shiftcount) & 15; 01085 if (nibble < 10) 01086 Out << (unsigned char)(nibble + '0'); 01087 else 01088 Out << (unsigned char)(nibble - 10 + 'A'); 01089 if (shiftcount == 0 && j+4 < width) { 01090 word = *(++p); 01091 shiftcount = 64; 01092 if (width-j-4 < 64) 01093 shiftcount = width-j-4; 01094 } 01095 } 01096 return; 01097 } 01098 01099 if (isa<ConstantAggregateZero>(CV)) { 01100 Out << "zeroinitializer"; 01101 return; 01102 } 01103 01104 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 01105 Out << "blockaddress("; 01106 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 01107 Context); 01108 Out << ", "; 01109 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 01110 Context); 01111 Out << ")"; 01112 return; 01113 } 01114 01115 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 01116 Type *ETy = CA->getType()->getElementType(); 01117 Out << '['; 01118 TypePrinter.print(ETy, Out); 01119 Out << ' '; 01120 WriteAsOperandInternal(Out, CA->getOperand(0), 01121 &TypePrinter, Machine, 01122 Context); 01123 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 01124 Out << ", "; 01125 TypePrinter.print(ETy, Out); 01126 Out << ' '; 01127 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 01128 Context); 01129 } 01130 Out << ']'; 01131 return; 01132 } 01133 01134 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) { 01135 // As a special case, print the array as a string if it is an array of 01136 // i8 with ConstantInt values. 01137 if (CA->isString()) { 01138 Out << "c\""; 01139 PrintEscapedString(CA->getAsString(), Out); 01140 Out << '"'; 01141 return; 01142 } 01143 01144 Type *ETy = CA->getType()->getElementType(); 01145 Out << '['; 01146 TypePrinter.print(ETy, Out); 01147 Out << ' '; 01148 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), 01149 &TypePrinter, Machine, 01150 Context); 01151 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) { 01152 Out << ", "; 01153 TypePrinter.print(ETy, Out); 01154 Out << ' '; 01155 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter, 01156 Machine, Context); 01157 } 01158 Out << ']'; 01159 return; 01160 } 01161 01162 01163 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 01164 if (CS->getType()->isPacked()) 01165 Out << '<'; 01166 Out << '{'; 01167 unsigned N = CS->getNumOperands(); 01168 if (N) { 01169 Out << ' '; 01170 TypePrinter.print(CS->getOperand(0)->getType(), Out); 01171 Out << ' '; 01172 01173 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 01174 Context); 01175 01176 for (unsigned i = 1; i < N; i++) { 01177 Out << ", "; 01178 TypePrinter.print(CS->getOperand(i)->getType(), Out); 01179 Out << ' '; 01180 01181 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 01182 Context); 01183 } 01184 Out << ' '; 01185 } 01186 01187 Out << '}'; 01188 if (CS->getType()->isPacked()) 01189 Out << '>'; 01190 return; 01191 } 01192 01193 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) { 01194 Type *ETy = CV->getType()->getVectorElementType(); 01195 Out << '<'; 01196 TypePrinter.print(ETy, Out); 01197 Out << ' '; 01198 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter, 01199 Machine, Context); 01200 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){ 01201 Out << ", "; 01202 TypePrinter.print(ETy, Out); 01203 Out << ' '; 01204 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter, 01205 Machine, Context); 01206 } 01207 Out << '>'; 01208 return; 01209 } 01210 01211 if (isa<ConstantPointerNull>(CV)) { 01212 Out << "null"; 01213 return; 01214 } 01215 01216 if (isa<UndefValue>(CV)) { 01217 Out << "undef"; 01218 return; 01219 } 01220 01221 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 01222 Out << CE->getOpcodeName(); 01223 WriteOptimizationInfo(Out, CE); 01224 if (CE->isCompare()) 01225 Out << ' ' << getPredicateText(CE->getPredicate()); 01226 Out << " ("; 01227 01228 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 01229 TypePrinter.print((*OI)->getType(), Out); 01230 Out << ' '; 01231 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 01232 if (OI+1 != CE->op_end()) 01233 Out << ", "; 01234 } 01235 01236 if (CE->hasIndices()) { 01237 ArrayRef<unsigned> Indices = CE->getIndices(); 01238 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 01239 Out << ", " << Indices[i]; 01240 } 01241 01242 if (CE->isCast()) { 01243 Out << " to "; 01244 TypePrinter.print(CE->getType(), Out); 01245 } 01246 01247 Out << ')'; 01248 return; 01249 } 01250 01251 Out << "<placeholder or erroneous Constant>"; 01252 } 01253 01254 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 01255 TypePrinting *TypePrinter, 01256 SlotTracker *Machine, 01257 const Module *Context) { 01258 Out << "!{"; 01259 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 01260 const Value *V = Node->getOperand(mi); 01261 if (!V) 01262 Out << "null"; 01263 else { 01264 TypePrinter->print(V->getType(), Out); 01265 Out << ' '; 01266 WriteAsOperandInternal(Out, Node->getOperand(mi), 01267 TypePrinter, Machine, Context); 01268 } 01269 if (mi + 1 != me) 01270 Out << ", "; 01271 } 01272 01273 Out << "}"; 01274 } 01275 01276 // Full implementation of printing a Value as an operand with support for 01277 // TypePrinting, etc. 01278 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 01279 TypePrinting *TypePrinter, 01280 SlotTracker *Machine, 01281 const Module *Context) { 01282 if (V->hasName()) { 01283 PrintLLVMName(Out, V); 01284 return; 01285 } 01286 01287 const Constant *CV = dyn_cast<Constant>(V); 01288 if (CV && !isa<GlobalValue>(CV)) { 01289 assert(TypePrinter && "Constants require TypePrinting!"); 01290 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 01291 return; 01292 } 01293 01294 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 01295 Out << "asm "; 01296 if (IA->hasSideEffects()) 01297 Out << "sideeffect "; 01298 if (IA->isAlignStack()) 01299 Out << "alignstack "; 01300 // We don't emit the AD_ATT dialect as it's the assumed default. 01301 if (IA->getDialect() == InlineAsm::AD_Intel) 01302 Out << "inteldialect "; 01303 Out << '"'; 01304 PrintEscapedString(IA->getAsmString(), Out); 01305 Out << "\", \""; 01306 PrintEscapedString(IA->getConstraintString(), Out); 01307 Out << '"'; 01308 return; 01309 } 01310 01311 if (const MDNode *N = dyn_cast<MDNode>(V)) { 01312 if (N->isFunctionLocal()) { 01313 // Print metadata inline, not via slot reference number. 01314 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context); 01315 return; 01316 } 01317 01318 if (!Machine) { 01319 if (N->isFunctionLocal()) 01320 Machine = new SlotTracker(N->getFunction()); 01321 else 01322 Machine = new SlotTracker(Context); 01323 } 01324 int Slot = Machine->getMetadataSlot(N); 01325 if (Slot == -1) 01326 Out << "<badref>"; 01327 else 01328 Out << '!' << Slot; 01329 return; 01330 } 01331 01332 if (const MDString *MDS = dyn_cast<MDString>(V)) { 01333 Out << "!\""; 01334 PrintEscapedString(MDS->getString(), Out); 01335 Out << '"'; 01336 return; 01337 } 01338 01339 char Prefix = '%'; 01340 int Slot; 01341 // If we have a SlotTracker, use it. 01342 if (Machine) { 01343 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 01344 Slot = Machine->getGlobalSlot(GV); 01345 Prefix = '@'; 01346 } else { 01347 Slot = Machine->getLocalSlot(V); 01348 01349 // If the local value didn't succeed, then we may be referring to a value 01350 // from a different function. Translate it, as this can happen when using 01351 // address of blocks. 01352 if (Slot == -1) 01353 if ((Machine = createSlotTracker(V))) { 01354 Slot = Machine->getLocalSlot(V); 01355 delete Machine; 01356 } 01357 } 01358 } else if ((Machine = createSlotTracker(V))) { 01359 // Otherwise, create one to get the # and then destroy it. 01360 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 01361 Slot = Machine->getGlobalSlot(GV); 01362 Prefix = '@'; 01363 } else { 01364 Slot = Machine->getLocalSlot(V); 01365 } 01366 delete Machine; 01367 Machine = nullptr; 01368 } else { 01369 Slot = -1; 01370 } 01371 01372 if (Slot != -1) 01373 Out << Prefix << Slot; 01374 else 01375 Out << "<badref>"; 01376 } 01377 01378 void AssemblyWriter::init() { 01379 if (!TheModule) 01380 return; 01381 TypePrinter.incorporateTypes(*TheModule); 01382 for (const Function &F : *TheModule) 01383 if (const Comdat *C = F.getComdat()) 01384 Comdats.insert(C); 01385 for (const GlobalVariable &GV : TheModule->globals()) 01386 if (const Comdat *C = GV.getComdat()) 01387 Comdats.insert(C); 01388 } 01389 01390 01391 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 01392 const Module *M, 01393 AssemblyAnnotationWriter *AAW) 01394 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) { 01395 init(); 01396 } 01397 01398 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M, 01399 AssemblyAnnotationWriter *AAW) 01400 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)), 01401 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) { 01402 init(); 01403 } 01404 01405 AssemblyWriter::~AssemblyWriter() { } 01406 01407 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 01408 if (!Operand) { 01409 Out << "<null operand!>"; 01410 return; 01411 } 01412 if (PrintType) { 01413 TypePrinter.print(Operand->getType(), Out); 01414 Out << ' '; 01415 } 01416 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 01417 } 01418 01419 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering, 01420 SynchronizationScope SynchScope) { 01421 if (Ordering == NotAtomic) 01422 return; 01423 01424 switch (SynchScope) { 01425 case SingleThread: Out << " singlethread"; break; 01426 case CrossThread: break; 01427 } 01428 01429 switch (Ordering) { 01430 default: Out << " <bad ordering " << int(Ordering) << ">"; break; 01431 case Unordered: Out << " unordered"; break; 01432 case Monotonic: Out << " monotonic"; break; 01433 case Acquire: Out << " acquire"; break; 01434 case Release: Out << " release"; break; 01435 case AcquireRelease: Out << " acq_rel"; break; 01436 case SequentiallyConsistent: Out << " seq_cst"; break; 01437 } 01438 } 01439 01440 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering, 01441 AtomicOrdering FailureOrdering, 01442 SynchronizationScope SynchScope) { 01443 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic); 01444 01445 switch (SynchScope) { 01446 case SingleThread: Out << " singlethread"; break; 01447 case CrossThread: break; 01448 } 01449 01450 switch (SuccessOrdering) { 01451 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break; 01452 case Unordered: Out << " unordered"; break; 01453 case Monotonic: Out << " monotonic"; break; 01454 case Acquire: Out << " acquire"; break; 01455 case Release: Out << " release"; break; 01456 case AcquireRelease: Out << " acq_rel"; break; 01457 case SequentiallyConsistent: Out << " seq_cst"; break; 01458 } 01459 01460 switch (FailureOrdering) { 01461 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break; 01462 case Unordered: Out << " unordered"; break; 01463 case Monotonic: Out << " monotonic"; break; 01464 case Acquire: Out << " acquire"; break; 01465 case Release: Out << " release"; break; 01466 case AcquireRelease: Out << " acq_rel"; break; 01467 case SequentiallyConsistent: Out << " seq_cst"; break; 01468 } 01469 } 01470 01471 void AssemblyWriter::writeParamOperand(const Value *Operand, 01472 AttributeSet Attrs, unsigned Idx) { 01473 if (!Operand) { 01474 Out << "<null operand!>"; 01475 return; 01476 } 01477 01478 // Print the type 01479 TypePrinter.print(Operand->getType(), Out); 01480 // Print parameter attributes list 01481 if (Attrs.hasAttributes(Idx)) 01482 Out << ' ' << Attrs.getAsString(Idx); 01483 Out << ' '; 01484 // Print the operand 01485 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 01486 } 01487 01488 void AssemblyWriter::printModule(const Module *M) { 01489 Machine.initialize(); 01490 01491 if (shouldPreserveAssemblyUseListOrder()) 01492 UseListOrders = predictUseListOrder(M); 01493 01494 if (!M->getModuleIdentifier().empty() && 01495 // Don't print the ID if it will start a new line (which would 01496 // require a comment char before it). 01497 M->getModuleIdentifier().find('\n') == std::string::npos) 01498 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 01499 01500 const std::string &DL = M->getDataLayoutStr(); 01501 if (!DL.empty()) 01502 Out << "target datalayout = \"" << DL << "\"\n"; 01503 if (!M->getTargetTriple().empty()) 01504 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 01505 01506 if (!M->getModuleInlineAsm().empty()) { 01507 // Split the string into lines, to make it easier to read the .ll file. 01508 std::string Asm = M->getModuleInlineAsm(); 01509 size_t CurPos = 0; 01510 size_t NewLine = Asm.find_first_of('\n', CurPos); 01511 Out << '\n'; 01512 while (NewLine != std::string::npos) { 01513 // We found a newline, print the portion of the asm string from the 01514 // last newline up to this newline. 01515 Out << "module asm \""; 01516 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 01517 Out); 01518 Out << "\"\n"; 01519 CurPos = NewLine+1; 01520 NewLine = Asm.find_first_of('\n', CurPos); 01521 } 01522 std::string rest(Asm.begin()+CurPos, Asm.end()); 01523 if (!rest.empty()) { 01524 Out << "module asm \""; 01525 PrintEscapedString(rest, Out); 01526 Out << "\"\n"; 01527 } 01528 } 01529 01530 printTypeIdentities(); 01531 01532 // Output all comdats. 01533 if (!Comdats.empty()) 01534 Out << '\n'; 01535 for (const Comdat *C : Comdats) { 01536 printComdat(C); 01537 if (C != Comdats.back()) 01538 Out << '\n'; 01539 } 01540 01541 // Output all globals. 01542 if (!M->global_empty()) Out << '\n'; 01543 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 01544 I != E; ++I) { 01545 printGlobal(I); Out << '\n'; 01546 } 01547 01548 // Output all aliases. 01549 if (!M->alias_empty()) Out << "\n"; 01550 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); 01551 I != E; ++I) 01552 printAlias(I); 01553 01554 // Output global use-lists. 01555 printUseLists(nullptr); 01556 01557 // Output all of the functions. 01558 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 01559 printFunction(I); 01560 assert(UseListOrders.empty() && "All use-lists should have been consumed"); 01561 01562 // Output all attribute groups. 01563 if (!Machine.as_empty()) { 01564 Out << '\n'; 01565 writeAllAttributeGroups(); 01566 } 01567 01568 // Output named metadata. 01569 if (!M->named_metadata_empty()) Out << '\n'; 01570 01571 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 01572 E = M->named_metadata_end(); I != E; ++I) 01573 printNamedMDNode(I); 01574 01575 // Output metadata. 01576 if (!Machine.mdn_empty()) { 01577 Out << '\n'; 01578 writeAllMDNodes(); 01579 } 01580 } 01581 01582 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 01583 Out << '!'; 01584 StringRef Name = NMD->getName(); 01585 if (Name.empty()) { 01586 Out << "<empty name> "; 01587 } else { 01588 if (isalpha(static_cast<unsigned char>(Name[0])) || 01589 Name[0] == '-' || Name[0] == '$' || 01590 Name[0] == '.' || Name[0] == '_') 01591 Out << Name[0]; 01592 else 01593 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 01594 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 01595 unsigned char C = Name[i]; 01596 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 01597 C == '.' || C == '_') 01598 Out << C; 01599 else 01600 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 01601 } 01602 } 01603 Out << " = !{"; 01604 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 01605 if (i) Out << ", "; 01606 int Slot = Machine.getMetadataSlot(NMD->getOperand(i)); 01607 if (Slot == -1) 01608 Out << "<badref>"; 01609 else 01610 Out << '!' << Slot; 01611 } 01612 Out << "}\n"; 01613 } 01614 01615 01616 static void PrintLinkage(GlobalValue::LinkageTypes LT, 01617 formatted_raw_ostream &Out) { 01618 switch (LT) { 01619 case GlobalValue::ExternalLinkage: break; 01620 case GlobalValue::PrivateLinkage: Out << "private "; break; 01621 case GlobalValue::InternalLinkage: Out << "internal "; break; 01622 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break; 01623 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break; 01624 case GlobalValue::WeakAnyLinkage: Out << "weak "; break; 01625 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break; 01626 case GlobalValue::CommonLinkage: Out << "common "; break; 01627 case GlobalValue::AppendingLinkage: Out << "appending "; break; 01628 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 01629 case GlobalValue::AvailableExternallyLinkage: 01630 Out << "available_externally "; 01631 break; 01632 } 01633 } 01634 01635 01636 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 01637 formatted_raw_ostream &Out) { 01638 switch (Vis) { 01639 case GlobalValue::DefaultVisibility: break; 01640 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 01641 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 01642 } 01643 } 01644 01645 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 01646 formatted_raw_ostream &Out) { 01647 switch (SCT) { 01648 case GlobalValue::DefaultStorageClass: break; 01649 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 01650 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 01651 } 01652 } 01653 01654 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 01655 formatted_raw_ostream &Out) { 01656 switch (TLM) { 01657 case GlobalVariable::NotThreadLocal: 01658 break; 01659 case GlobalVariable::GeneralDynamicTLSModel: 01660 Out << "thread_local "; 01661 break; 01662 case GlobalVariable::LocalDynamicTLSModel: 01663 Out << "thread_local(localdynamic) "; 01664 break; 01665 case GlobalVariable::InitialExecTLSModel: 01666 Out << "thread_local(initialexec) "; 01667 break; 01668 case GlobalVariable::LocalExecTLSModel: 01669 Out << "thread_local(localexec) "; 01670 break; 01671 } 01672 } 01673 01674 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 01675 if (GV->isMaterializable()) 01676 Out << "; Materializable\n"; 01677 01678 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 01679 Out << " = "; 01680 01681 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 01682 Out << "external "; 01683 01684 PrintLinkage(GV->getLinkage(), Out); 01685 PrintVisibility(GV->getVisibility(), Out); 01686 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 01687 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 01688 if (GV->hasUnnamedAddr()) 01689 Out << "unnamed_addr "; 01690 01691 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 01692 Out << "addrspace(" << AddressSpace << ") "; 01693 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 01694 Out << (GV->isConstant() ? "constant " : "global "); 01695 TypePrinter.print(GV->getType()->getElementType(), Out); 01696 01697 if (GV->hasInitializer()) { 01698 Out << ' '; 01699 writeOperand(GV->getInitializer(), false); 01700 } 01701 01702 if (GV->hasSection()) { 01703 Out << ", section \""; 01704 PrintEscapedString(GV->getSection(), Out); 01705 Out << '"'; 01706 } 01707 if (GV->hasComdat()) { 01708 Out << ", comdat "; 01709 PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix); 01710 } 01711 if (GV->getAlignment()) 01712 Out << ", align " << GV->getAlignment(); 01713 01714 printInfoComment(*GV); 01715 } 01716 01717 void AssemblyWriter::printAlias(const GlobalAlias *GA) { 01718 if (GA->isMaterializable()) 01719 Out << "; Materializable\n"; 01720 01721 // Don't crash when dumping partially built GA 01722 if (!GA->hasName()) 01723 Out << "<<nameless>> = "; 01724 else { 01725 PrintLLVMName(Out, GA); 01726 Out << " = "; 01727 } 01728 PrintLinkage(GA->getLinkage(), Out); 01729 PrintVisibility(GA->getVisibility(), Out); 01730 PrintDLLStorageClass(GA->getDLLStorageClass(), Out); 01731 PrintThreadLocalModel(GA->getThreadLocalMode(), Out); 01732 if (GA->hasUnnamedAddr()) 01733 Out << "unnamed_addr "; 01734 01735 Out << "alias "; 01736 01737 const Constant *Aliasee = GA->getAliasee(); 01738 01739 if (!Aliasee) { 01740 TypePrinter.print(GA->getType(), Out); 01741 Out << " <<NULL ALIASEE>>"; 01742 } else { 01743 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee)); 01744 } 01745 01746 printInfoComment(*GA); 01747 Out << '\n'; 01748 } 01749 01750 void AssemblyWriter::printComdat(const Comdat *C) { 01751 C->print(Out); 01752 } 01753 01754 void AssemblyWriter::printTypeIdentities() { 01755 if (TypePrinter.NumberedTypes.empty() && 01756 TypePrinter.NamedTypes.empty()) 01757 return; 01758 01759 Out << '\n'; 01760 01761 // We know all the numbers that each type is used and we know that it is a 01762 // dense assignment. Convert the map to an index table. 01763 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size()); 01764 for (DenseMap<StructType*, unsigned>::iterator I = 01765 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end(); 01766 I != E; ++I) { 01767 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?"); 01768 NumberedTypes[I->second] = I->first; 01769 } 01770 01771 // Emit all numbered types. 01772 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 01773 Out << '%' << i << " = type "; 01774 01775 // Make sure we print out at least one level of the type structure, so 01776 // that we do not get %2 = type %2 01777 TypePrinter.printStructBody(NumberedTypes[i], Out); 01778 Out << '\n'; 01779 } 01780 01781 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) { 01782 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix); 01783 Out << " = type "; 01784 01785 // Make sure we print out at least one level of the type structure, so 01786 // that we do not get %FILE = type %FILE 01787 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out); 01788 Out << '\n'; 01789 } 01790 } 01791 01792 /// printFunction - Print all aspects of a function. 01793 /// 01794 void AssemblyWriter::printFunction(const Function *F) { 01795 // Print out the return type and name. 01796 Out << '\n'; 01797 01798 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 01799 01800 if (F->isMaterializable()) 01801 Out << "; Materializable\n"; 01802 01803 const AttributeSet &Attrs = F->getAttributes(); 01804 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) { 01805 AttributeSet AS = Attrs.getFnAttributes(); 01806 std::string AttrStr; 01807 01808 unsigned Idx = 0; 01809 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx) 01810 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex) 01811 break; 01812 01813 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx); 01814 I != E; ++I) { 01815 Attribute Attr = *I; 01816 if (!Attr.isStringAttribute()) { 01817 if (!AttrStr.empty()) AttrStr += ' '; 01818 AttrStr += Attr.getAsString(); 01819 } 01820 } 01821 01822 if (!AttrStr.empty()) 01823 Out << "; Function Attrs: " << AttrStr << '\n'; 01824 } 01825 01826 if (F->isDeclaration()) 01827 Out << "declare "; 01828 else 01829 Out << "define "; 01830 01831 PrintLinkage(F->getLinkage(), Out); 01832 PrintVisibility(F->getVisibility(), Out); 01833 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 01834 01835 // Print the calling convention. 01836 if (F->getCallingConv() != CallingConv::C) { 01837 PrintCallingConv(F->getCallingConv(), Out); 01838 Out << " "; 01839 } 01840 01841 FunctionType *FT = F->getFunctionType(); 01842 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 01843 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' '; 01844 TypePrinter.print(F->getReturnType(), Out); 01845 Out << ' '; 01846 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 01847 Out << '('; 01848 Machine.incorporateFunction(F); 01849 01850 // Loop over the arguments, printing them... 01851 01852 unsigned Idx = 1; 01853 if (!F->isDeclaration()) { 01854 // If this isn't a declaration, print the argument names as well. 01855 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 01856 I != E; ++I) { 01857 // Insert commas as we go... the first arg doesn't get a comma 01858 if (I != F->arg_begin()) Out << ", "; 01859 printArgument(I, Attrs, Idx); 01860 Idx++; 01861 } 01862 } else { 01863 // Otherwise, print the types from the function type. 01864 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 01865 // Insert commas as we go... the first arg doesn't get a comma 01866 if (i) Out << ", "; 01867 01868 // Output type... 01869 TypePrinter.print(FT->getParamType(i), Out); 01870 01871 if (Attrs.hasAttributes(i+1)) 01872 Out << ' ' << Attrs.getAsString(i+1); 01873 } 01874 } 01875 01876 // Finish printing arguments... 01877 if (FT->isVarArg()) { 01878 if (FT->getNumParams()) Out << ", "; 01879 Out << "..."; // Output varargs portion of signature! 01880 } 01881 Out << ')'; 01882 if (F->hasUnnamedAddr()) 01883 Out << " unnamed_addr"; 01884 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 01885 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 01886 if (F->hasSection()) { 01887 Out << " section \""; 01888 PrintEscapedString(F->getSection(), Out); 01889 Out << '"'; 01890 } 01891 if (F->hasComdat()) { 01892 Out << " comdat "; 01893 PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix); 01894 } 01895 if (F->getAlignment()) 01896 Out << " align " << F->getAlignment(); 01897 if (F->hasGC()) 01898 Out << " gc \"" << F->getGC() << '"'; 01899 if (F->hasPrefixData()) { 01900 Out << " prefix "; 01901 writeOperand(F->getPrefixData(), true); 01902 } 01903 if (F->isDeclaration()) { 01904 Out << '\n'; 01905 } else { 01906 Out << " {"; 01907 // Output all of the function's basic blocks. 01908 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 01909 printBasicBlock(I); 01910 01911 // Output the function's use-lists. 01912 printUseLists(F); 01913 01914 Out << "}\n"; 01915 } 01916 01917 Machine.purgeFunction(); 01918 } 01919 01920 /// printArgument - This member is called for every argument that is passed into 01921 /// the function. Simply print it out 01922 /// 01923 void AssemblyWriter::printArgument(const Argument *Arg, 01924 AttributeSet Attrs, unsigned Idx) { 01925 // Output type... 01926 TypePrinter.print(Arg->getType(), Out); 01927 01928 // Output parameter attributes list 01929 if (Attrs.hasAttributes(Idx)) 01930 Out << ' ' << Attrs.getAsString(Idx); 01931 01932 // Output name, if available... 01933 if (Arg->hasName()) { 01934 Out << ' '; 01935 PrintLLVMName(Out, Arg); 01936 } 01937 } 01938 01939 /// printBasicBlock - This member is called for each basic block in a method. 01940 /// 01941 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 01942 if (BB->hasName()) { // Print out the label if it exists... 01943 Out << "\n"; 01944 PrintLLVMName(Out, BB->getName(), LabelPrefix); 01945 Out << ':'; 01946 } else if (!BB->use_empty()) { // Don't print block # of no uses... 01947 Out << "\n; <label>:"; 01948 int Slot = Machine.getLocalSlot(BB); 01949 if (Slot != -1) 01950 Out << Slot; 01951 else 01952 Out << "<badref>"; 01953 } 01954 01955 if (!BB->getParent()) { 01956 Out.PadToColumn(50); 01957 Out << "; Error: Block without parent!"; 01958 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 01959 // Output predecessors for the block. 01960 Out.PadToColumn(50); 01961 Out << ";"; 01962 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 01963 01964 if (PI == PE) { 01965 Out << " No predecessors!"; 01966 } else { 01967 Out << " preds = "; 01968 writeOperand(*PI, false); 01969 for (++PI; PI != PE; ++PI) { 01970 Out << ", "; 01971 writeOperand(*PI, false); 01972 } 01973 } 01974 } 01975 01976 Out << "\n"; 01977 01978 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 01979 01980 // Output all of the instructions in the basic block... 01981 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 01982 printInstructionLine(*I); 01983 } 01984 01985 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 01986 } 01987 01988 /// printInstructionLine - Print an instruction and a newline character. 01989 void AssemblyWriter::printInstructionLine(const Instruction &I) { 01990 printInstruction(I); 01991 Out << '\n'; 01992 } 01993 01994 /// printInfoComment - Print a little comment after the instruction indicating 01995 /// which slot it occupies. 01996 /// 01997 void AssemblyWriter::printInfoComment(const Value &V) { 01998 if (AnnotationWriter) 01999 AnnotationWriter->printInfoComment(V, Out); 02000 } 02001 02002 // This member is called for each Instruction in a function.. 02003 void AssemblyWriter::printInstruction(const Instruction &I) { 02004 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 02005 02006 // Print out indentation for an instruction. 02007 Out << " "; 02008 02009 // Print out name if it exists... 02010 if (I.hasName()) { 02011 PrintLLVMName(Out, &I); 02012 Out << " = "; 02013 } else if (!I.getType()->isVoidTy()) { 02014 // Print out the def slot taken. 02015 int SlotNum = Machine.getLocalSlot(&I); 02016 if (SlotNum == -1) 02017 Out << "<badref> = "; 02018 else 02019 Out << '%' << SlotNum << " = "; 02020 } 02021 02022 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 02023 if (CI->isMustTailCall()) 02024 Out << "musttail "; 02025 else if (CI->isTailCall()) 02026 Out << "tail "; 02027 } 02028 02029 // Print out the opcode... 02030 Out << I.getOpcodeName(); 02031 02032 // If this is an atomic load or store, print out the atomic marker. 02033 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 02034 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 02035 Out << " atomic"; 02036 02037 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 02038 Out << " weak"; 02039 02040 // If this is a volatile operation, print out the volatile marker. 02041 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 02042 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 02043 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 02044 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 02045 Out << " volatile"; 02046 02047 // Print out optimization information. 02048 WriteOptimizationInfo(Out, &I); 02049 02050 // Print out the compare instruction predicates 02051 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 02052 Out << ' ' << getPredicateText(CI->getPredicate()); 02053 02054 // Print out the atomicrmw operation 02055 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 02056 writeAtomicRMWOperation(Out, RMWI->getOperation()); 02057 02058 // Print out the type of the operands... 02059 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 02060 02061 // Special case conditional branches to swizzle the condition out to the front 02062 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 02063 const BranchInst &BI(cast<BranchInst>(I)); 02064 Out << ' '; 02065 writeOperand(BI.getCondition(), true); 02066 Out << ", "; 02067 writeOperand(BI.getSuccessor(0), true); 02068 Out << ", "; 02069 writeOperand(BI.getSuccessor(1), true); 02070 02071 } else if (isa<SwitchInst>(I)) { 02072 const SwitchInst& SI(cast<SwitchInst>(I)); 02073 // Special case switch instruction to get formatting nice and correct. 02074 Out << ' '; 02075 writeOperand(SI.getCondition(), true); 02076 Out << ", "; 02077 writeOperand(SI.getDefaultDest(), true); 02078 Out << " ["; 02079 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end(); 02080 i != e; ++i) { 02081 Out << "\n "; 02082 writeOperand(i.getCaseValue(), true); 02083 Out << ", "; 02084 writeOperand(i.getCaseSuccessor(), true); 02085 } 02086 Out << "\n ]"; 02087 } else if (isa<IndirectBrInst>(I)) { 02088 // Special case indirectbr instruction to get formatting nice and correct. 02089 Out << ' '; 02090 writeOperand(Operand, true); 02091 Out << ", ["; 02092 02093 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 02094 if (i != 1) 02095 Out << ", "; 02096 writeOperand(I.getOperand(i), true); 02097 } 02098 Out << ']'; 02099 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 02100 Out << ' '; 02101 TypePrinter.print(I.getType(), Out); 02102 Out << ' '; 02103 02104 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 02105 if (op) Out << ", "; 02106 Out << "[ "; 02107 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 02108 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 02109 } 02110 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 02111 Out << ' '; 02112 writeOperand(I.getOperand(0), true); 02113 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 02114 Out << ", " << *i; 02115 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 02116 Out << ' '; 02117 writeOperand(I.getOperand(0), true); Out << ", "; 02118 writeOperand(I.getOperand(1), true); 02119 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 02120 Out << ", " << *i; 02121 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 02122 Out << ' '; 02123 TypePrinter.print(I.getType(), Out); 02124 Out << " personality "; 02125 writeOperand(I.getOperand(0), true); Out << '\n'; 02126 02127 if (LPI->isCleanup()) 02128 Out << " cleanup"; 02129 02130 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 02131 if (i != 0 || LPI->isCleanup()) Out << "\n"; 02132 if (LPI->isCatch(i)) 02133 Out << " catch "; 02134 else 02135 Out << " filter "; 02136 02137 writeOperand(LPI->getClause(i), true); 02138 } 02139 } else if (isa<ReturnInst>(I) && !Operand) { 02140 Out << " void"; 02141 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 02142 // Print the calling convention being used. 02143 if (CI->getCallingConv() != CallingConv::C) { 02144 Out << " "; 02145 PrintCallingConv(CI->getCallingConv(), Out); 02146 } 02147 02148 Operand = CI->getCalledValue(); 02149 PointerType *PTy = cast<PointerType>(Operand->getType()); 02150 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 02151 Type *RetTy = FTy->getReturnType(); 02152 const AttributeSet &PAL = CI->getAttributes(); 02153 02154 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 02155 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 02156 02157 // If possible, print out the short form of the call instruction. We can 02158 // only do this if the first argument is a pointer to a nonvararg function, 02159 // and if the return type is not a pointer to a function. 02160 // 02161 Out << ' '; 02162 if (!FTy->isVarArg() && 02163 (!RetTy->isPointerTy() || 02164 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 02165 TypePrinter.print(RetTy, Out); 02166 Out << ' '; 02167 writeOperand(Operand, false); 02168 } else { 02169 writeOperand(Operand, true); 02170 } 02171 Out << '('; 02172 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 02173 if (op > 0) 02174 Out << ", "; 02175 writeParamOperand(CI->getArgOperand(op), PAL, op + 1); 02176 } 02177 02178 // Emit an ellipsis if this is a musttail call in a vararg function. This 02179 // is only to aid readability, musttail calls forward varargs by default. 02180 if (CI->isMustTailCall() && CI->getParent() && 02181 CI->getParent()->getParent() && 02182 CI->getParent()->getParent()->isVarArg()) 02183 Out << ", ..."; 02184 02185 Out << ')'; 02186 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 02187 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 02188 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 02189 Operand = II->getCalledValue(); 02190 PointerType *PTy = cast<PointerType>(Operand->getType()); 02191 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 02192 Type *RetTy = FTy->getReturnType(); 02193 const AttributeSet &PAL = II->getAttributes(); 02194 02195 // Print the calling convention being used. 02196 if (II->getCallingConv() != CallingConv::C) { 02197 Out << " "; 02198 PrintCallingConv(II->getCallingConv(), Out); 02199 } 02200 02201 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 02202 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 02203 02204 // If possible, print out the short form of the invoke instruction. We can 02205 // only do this if the first argument is a pointer to a nonvararg function, 02206 // and if the return type is not a pointer to a function. 02207 // 02208 Out << ' '; 02209 if (!FTy->isVarArg() && 02210 (!RetTy->isPointerTy() || 02211 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 02212 TypePrinter.print(RetTy, Out); 02213 Out << ' '; 02214 writeOperand(Operand, false); 02215 } else { 02216 writeOperand(Operand, true); 02217 } 02218 Out << '('; 02219 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 02220 if (op) 02221 Out << ", "; 02222 writeParamOperand(II->getArgOperand(op), PAL, op + 1); 02223 } 02224 02225 Out << ')'; 02226 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 02227 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 02228 02229 Out << "\n to "; 02230 writeOperand(II->getNormalDest(), true); 02231 Out << " unwind "; 02232 writeOperand(II->getUnwindDest(), true); 02233 02234 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 02235 Out << ' '; 02236 if (AI->isUsedWithInAlloca()) 02237 Out << "inalloca "; 02238 TypePrinter.print(AI->getAllocatedType(), Out); 02239 if (!AI->getArraySize() || AI->isArrayAllocation()) { 02240 Out << ", "; 02241 writeOperand(AI->getArraySize(), true); 02242 } 02243 if (AI->getAlignment()) { 02244 Out << ", align " << AI->getAlignment(); 02245 } 02246 } else if (isa<CastInst>(I)) { 02247 if (Operand) { 02248 Out << ' '; 02249 writeOperand(Operand, true); // Work with broken code 02250 } 02251 Out << " to "; 02252 TypePrinter.print(I.getType(), Out); 02253 } else if (isa<VAArgInst>(I)) { 02254 if (Operand) { 02255 Out << ' '; 02256 writeOperand(Operand, true); // Work with broken code 02257 } 02258 Out << ", "; 02259 TypePrinter.print(I.getType(), Out); 02260 } else if (Operand) { // Print the normal way. 02261 02262 // PrintAllTypes - Instructions who have operands of all the same type 02263 // omit the type from all but the first operand. If the instruction has 02264 // different type operands (for example br), then they are all printed. 02265 bool PrintAllTypes = false; 02266 Type *TheType = Operand->getType(); 02267 02268 // Select, Store and ShuffleVector always print all types. 02269 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 02270 || isa<ReturnInst>(I)) { 02271 PrintAllTypes = true; 02272 } else { 02273 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 02274 Operand = I.getOperand(i); 02275 // note that Operand shouldn't be null, but the test helps make dump() 02276 // more tolerant of malformed IR 02277 if (Operand && Operand->getType() != TheType) { 02278 PrintAllTypes = true; // We have differing types! Print them all! 02279 break; 02280 } 02281 } 02282 } 02283 02284 if (!PrintAllTypes) { 02285 Out << ' '; 02286 TypePrinter.print(TheType, Out); 02287 } 02288 02289 Out << ' '; 02290 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 02291 if (i) Out << ", "; 02292 writeOperand(I.getOperand(i), PrintAllTypes); 02293 } 02294 } 02295 02296 // Print atomic ordering/alignment for memory operations 02297 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 02298 if (LI->isAtomic()) 02299 writeAtomic(LI->getOrdering(), LI->getSynchScope()); 02300 if (LI->getAlignment()) 02301 Out << ", align " << LI->getAlignment(); 02302 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 02303 if (SI->isAtomic()) 02304 writeAtomic(SI->getOrdering(), SI->getSynchScope()); 02305 if (SI->getAlignment()) 02306 Out << ", align " << SI->getAlignment(); 02307 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 02308 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(), 02309 CXI->getSynchScope()); 02310 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 02311 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope()); 02312 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 02313 writeAtomic(FI->getOrdering(), FI->getSynchScope()); 02314 } 02315 02316 // Print Metadata info. 02317 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD; 02318 I.getAllMetadata(InstMD); 02319 if (!InstMD.empty()) { 02320 SmallVector<StringRef, 8> MDNames; 02321 I.getType()->getContext().getMDKindNames(MDNames); 02322 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) { 02323 unsigned Kind = InstMD[i].first; 02324 if (Kind < MDNames.size()) { 02325 Out << ", !" << MDNames[Kind]; 02326 } else { 02327 Out << ", !<unknown kind #" << Kind << ">"; 02328 } 02329 Out << ' '; 02330 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine, 02331 TheModule); 02332 } 02333 } 02334 printInfoComment(I); 02335 } 02336 02337 static void WriteMDNodeComment(const MDNode *Node, 02338 formatted_raw_ostream &Out) { 02339 if (Node->getNumOperands() < 1) 02340 return; 02341 02342 Value *Op = Node->getOperand(0); 02343 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32) 02344 return; 02345 02346 DIDescriptor Desc(Node); 02347 if (!Desc.Verify()) 02348 return; 02349 02350 unsigned Tag = Desc.getTag(); 02351 Out.PadToColumn(50); 02352 if (dwarf::TagString(Tag)) { 02353 Out << "; "; 02354 Desc.print(Out); 02355 } else if (Tag == dwarf::DW_TAG_user_base) { 02356 Out << "; [ DW_TAG_user_base ]"; 02357 } 02358 } 02359 02360 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 02361 Out << '!' << Slot << " = metadata "; 02362 printMDNodeBody(Node); 02363 } 02364 02365 void AssemblyWriter::writeAllMDNodes() { 02366 SmallVector<const MDNode *, 16> Nodes; 02367 Nodes.resize(Machine.mdn_size()); 02368 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 02369 I != E; ++I) 02370 Nodes[I->second] = cast<MDNode>(I->first); 02371 02372 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 02373 writeMDNode(i, Nodes[i]); 02374 } 02375 } 02376 02377 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 02378 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 02379 WriteMDNodeComment(Node, Out); 02380 Out << "\n"; 02381 } 02382 02383 void AssemblyWriter::writeAllAttributeGroups() { 02384 std::vector<std::pair<AttributeSet, unsigned> > asVec; 02385 asVec.resize(Machine.as_size()); 02386 02387 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end(); 02388 I != E; ++I) 02389 asVec[I->second] = *I; 02390 02391 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator 02392 I = asVec.begin(), E = asVec.end(); I != E; ++I) 02393 Out << "attributes #" << I->second << " = { " 02394 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n"; 02395 } 02396 02397 } // namespace llvm 02398 02399 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) { 02400 bool IsInFunction = Machine.getFunction(); 02401 if (IsInFunction) 02402 Out << " "; 02403 02404 Out << "uselistorder"; 02405 if (const BasicBlock *BB = 02406 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) { 02407 Out << "_bb "; 02408 writeOperand(BB->getParent(), false); 02409 Out << ", "; 02410 writeOperand(BB, false); 02411 } else { 02412 Out << " "; 02413 writeOperand(Order.V, true); 02414 } 02415 Out << ", { "; 02416 02417 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 02418 Out << Order.Shuffle[0]; 02419 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I) 02420 Out << ", " << Order.Shuffle[I]; 02421 Out << " }\n"; 02422 } 02423 02424 void AssemblyWriter::printUseLists(const Function *F) { 02425 auto hasMore = 02426 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; }; 02427 if (!hasMore()) 02428 // Nothing to do. 02429 return; 02430 02431 Out << "\n; uselistorder directives\n"; 02432 while (hasMore()) { 02433 printUseListOrder(UseListOrders.back()); 02434 UseListOrders.pop_back(); 02435 } 02436 } 02437 02438 //===----------------------------------------------------------------------===// 02439 // External Interface declarations 02440 //===----------------------------------------------------------------------===// 02441 02442 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 02443 SlotTracker SlotTable(this); 02444 formatted_raw_ostream OS(ROS); 02445 AssemblyWriter W(OS, SlotTable, this, AAW); 02446 W.printModule(this); 02447 } 02448 02449 void NamedMDNode::print(raw_ostream &ROS) const { 02450 SlotTracker SlotTable(getParent()); 02451 formatted_raw_ostream OS(ROS); 02452 AssemblyWriter W(OS, SlotTable, getParent(), nullptr); 02453 W.printNamedMDNode(this); 02454 } 02455 02456 void Comdat::print(raw_ostream &ROS) const { 02457 PrintLLVMName(ROS, getName(), ComdatPrefix); 02458 ROS << " = comdat "; 02459 02460 switch (getSelectionKind()) { 02461 case Comdat::Any: 02462 ROS << "any"; 02463 break; 02464 case Comdat::ExactMatch: 02465 ROS << "exactmatch"; 02466 break; 02467 case Comdat::Largest: 02468 ROS << "largest"; 02469 break; 02470 case Comdat::NoDuplicates: 02471 ROS << "noduplicates"; 02472 break; 02473 case Comdat::SameSize: 02474 ROS << "samesize"; 02475 break; 02476 } 02477 02478 ROS << '\n'; 02479 } 02480 02481 void Type::print(raw_ostream &OS) const { 02482 TypePrinting TP; 02483 TP.print(const_cast<Type*>(this), OS); 02484 02485 // If the type is a named struct type, print the body as well. 02486 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 02487 if (!STy->isLiteral()) { 02488 OS << " = type "; 02489 TP.printStructBody(STy, OS); 02490 } 02491 } 02492 02493 void Value::print(raw_ostream &ROS) const { 02494 formatted_raw_ostream OS(ROS); 02495 if (const Instruction *I = dyn_cast<Instruction>(this)) { 02496 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr; 02497 SlotTracker SlotTable(F); 02498 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr); 02499 W.printInstruction(*I); 02500 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 02501 SlotTracker SlotTable(BB->getParent()); 02502 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr); 02503 W.printBasicBlock(BB); 02504 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 02505 SlotTracker SlotTable(GV->getParent()); 02506 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr); 02507 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 02508 W.printGlobal(V); 02509 else if (const Function *F = dyn_cast<Function>(GV)) 02510 W.printFunction(F); 02511 else 02512 W.printAlias(cast<GlobalAlias>(GV)); 02513 } else if (const MDNode *N = dyn_cast<MDNode>(this)) { 02514 const Function *F = N->getFunction(); 02515 SlotTracker SlotTable(F); 02516 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr); 02517 W.printMDNodeBody(N); 02518 } else if (const Constant *C = dyn_cast<Constant>(this)) { 02519 TypePrinting TypePrinter; 02520 TypePrinter.print(C->getType(), OS); 02521 OS << ' '; 02522 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr); 02523 } else if (isa<InlineAsm>(this) || isa<MDString>(this) || 02524 isa<Argument>(this)) { 02525 this->printAsOperand(OS); 02526 } else { 02527 llvm_unreachable("Unknown value to print out!"); 02528 } 02529 } 02530 02531 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const { 02532 // Fast path: Don't construct and populate a TypePrinting object if we 02533 // won't be needing any types printed. 02534 if (!PrintType && 02535 ((!isa<Constant>(this) && !isa<MDNode>(this)) || 02536 hasName() || isa<GlobalValue>(this))) { 02537 WriteAsOperandInternal(O, this, nullptr, nullptr, M); 02538 return; 02539 } 02540 02541 if (!M) 02542 M = getModuleFromVal(this); 02543 02544 TypePrinting TypePrinter; 02545 if (M) 02546 TypePrinter.incorporateTypes(*M); 02547 if (PrintType) { 02548 TypePrinter.print(getType(), O); 02549 O << ' '; 02550 } 02551 02552 WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M); 02553 } 02554 02555 // Value::dump - allow easy printing of Values from the debugger. 02556 void Value::dump() const { print(dbgs()); dbgs() << '\n'; } 02557 02558 // Type::dump - allow easy printing of Types from the debugger. 02559 void Type::dump() const { print(dbgs()); dbgs() << '\n'; } 02560 02561 // Module::dump() - Allow printing of Modules from the debugger. 02562 void Module::dump() const { print(dbgs(), nullptr); } 02563 02564 // \brief Allow printing of Comdats from the debugger. 02565 void Comdat::dump() const { print(dbgs()); } 02566 02567 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 02568 void NamedMDNode::dump() const { print(dbgs()); }