AsmWriter.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395
  1. //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This library implements the functionality defined in llvm/IR/Writer.h
  11. //
  12. // Note that these routines must be extremely tolerant of various errors in the
  13. // LLVM code, because it can be used for debugging transformations.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/IR/AssemblyAnnotationWriter.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/CallingConv.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DebugInfo.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/IRPrintingPasses.h"
  28. #include "llvm/IR/InlineAsm.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ModuleSlotTracker.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "llvm/IR/Statepoint.h"
  35. #include "llvm/IR/TypeFinder.h"
  36. #include "llvm/IR/UseListOrder.h"
  37. #include "llvm/IR/ValueSymbolTable.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/Dwarf.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FormattedStream.h"
  42. #include "llvm/Support/MathExtras.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include <algorithm>
  45. #include <cctype>
  46. using namespace llvm;
  47. // Make virtual table appear in this compilation unit.
  48. AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
  49. //===----------------------------------------------------------------------===//
  50. // Helper Functions
  51. //===----------------------------------------------------------------------===//
  52. namespace {
  53. struct OrderMap {
  54. DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
  55. unsigned size() const { return IDs.size(); }
  56. std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
  57. std::pair<unsigned, bool> lookup(const Value *V) const {
  58. return IDs.lookup(V);
  59. }
  60. void index(const Value *V) {
  61. // Explicitly sequence get-size and insert-value operations to avoid UB.
  62. unsigned ID = IDs.size() + 1;
  63. IDs[V].first = ID;
  64. }
  65. };
  66. }
  67. static void orderValue(const Value *V, OrderMap &OM) {
  68. if (OM.lookup(V).first)
  69. return;
  70. if (const Constant *C = dyn_cast<Constant>(V))
  71. if (C->getNumOperands() && !isa<GlobalValue>(C))
  72. for (const Value *Op : C->operands())
  73. if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
  74. orderValue(Op, OM);
  75. // Note: we cannot cache this lookup above, since inserting into the map
  76. // changes the map's size, and thus affects the other IDs.
  77. OM.index(V);
  78. }
  79. static OrderMap orderModule(const Module *M) {
  80. // This needs to match the order used by ValueEnumerator::ValueEnumerator()
  81. // and ValueEnumerator::incorporateFunction().
  82. OrderMap OM;
  83. for (const GlobalVariable &G : M->globals()) {
  84. if (G.hasInitializer())
  85. if (!isa<GlobalValue>(G.getInitializer()))
  86. orderValue(G.getInitializer(), OM);
  87. orderValue(&G, OM);
  88. }
  89. for (const GlobalAlias &A : M->aliases()) {
  90. if (!isa<GlobalValue>(A.getAliasee()))
  91. orderValue(A.getAliasee(), OM);
  92. orderValue(&A, OM);
  93. }
  94. for (const Function &F : *M) {
  95. if (F.hasPrefixData())
  96. if (!isa<GlobalValue>(F.getPrefixData()))
  97. orderValue(F.getPrefixData(), OM);
  98. if (F.hasPrologueData())
  99. if (!isa<GlobalValue>(F.getPrologueData()))
  100. orderValue(F.getPrologueData(), OM);
  101. if (F.hasPersonalityFn())
  102. if (!isa<GlobalValue>(F.getPersonalityFn()))
  103. orderValue(F.getPersonalityFn(), OM);
  104. orderValue(&F, OM);
  105. if (F.isDeclaration())
  106. continue;
  107. for (const Argument &A : F.args())
  108. orderValue(&A, OM);
  109. for (const BasicBlock &BB : F) {
  110. orderValue(&BB, OM);
  111. for (const Instruction &I : BB) {
  112. for (const Value *Op : I.operands())
  113. if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
  114. isa<InlineAsm>(*Op))
  115. orderValue(Op, OM);
  116. orderValue(&I, OM);
  117. }
  118. }
  119. }
  120. return OM;
  121. }
  122. static void predictValueUseListOrderImpl(const Value *V, const Function *F,
  123. unsigned ID, const OrderMap &OM,
  124. UseListOrderStack &Stack) {
  125. // Predict use-list order for this one.
  126. typedef std::pair<const Use *, unsigned> Entry;
  127. SmallVector<Entry, 64> List;
  128. for (const Use &U : V->uses())
  129. // Check if this user will be serialized.
  130. if (OM.lookup(U.getUser()).first)
  131. List.push_back(std::make_pair(&U, List.size()));
  132. if (List.size() < 2)
  133. // We may have lost some users.
  134. return;
  135. bool GetsReversed =
  136. !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
  137. if (auto *BA = dyn_cast<BlockAddress>(V))
  138. ID = OM.lookup(BA->getBasicBlock()).first;
  139. std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
  140. const Use *LU = L.first;
  141. const Use *RU = R.first;
  142. if (LU == RU)
  143. return false;
  144. auto LID = OM.lookup(LU->getUser()).first;
  145. auto RID = OM.lookup(RU->getUser()).first;
  146. // If ID is 4, then expect: 7 6 5 1 2 3.
  147. if (LID < RID) {
  148. if (GetsReversed)
  149. if (RID <= ID)
  150. return true;
  151. return false;
  152. }
  153. if (RID < LID) {
  154. if (GetsReversed)
  155. if (LID <= ID)
  156. return false;
  157. return true;
  158. }
  159. // LID and RID are equal, so we have different operands of the same user.
  160. // Assume operands are added in order for all instructions.
  161. if (GetsReversed)
  162. if (LID <= ID)
  163. return LU->getOperandNo() < RU->getOperandNo();
  164. return LU->getOperandNo() > RU->getOperandNo();
  165. });
  166. if (std::is_sorted(
  167. List.begin(), List.end(),
  168. [](const Entry &L, const Entry &R) { return L.second < R.second; }))
  169. // Order is already correct.
  170. return;
  171. // Store the shuffle.
  172. Stack.emplace_back(V, F, List.size());
  173. assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
  174. for (size_t I = 0, E = List.size(); I != E; ++I)
  175. Stack.back().Shuffle[I] = List[I].second;
  176. }
  177. static void predictValueUseListOrder(const Value *V, const Function *F,
  178. OrderMap &OM, UseListOrderStack &Stack) {
  179. auto &IDPair = OM[V];
  180. assert(IDPair.first && "Unmapped value");
  181. if (IDPair.second)
  182. // Already predicted.
  183. return;
  184. // Do the actual prediction.
  185. IDPair.second = true;
  186. if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
  187. predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
  188. // Recursive descent into constants.
  189. if (const Constant *C = dyn_cast<Constant>(V))
  190. if (C->getNumOperands()) // Visit GlobalValues.
  191. for (const Value *Op : C->operands())
  192. if (isa<Constant>(Op)) // Visit GlobalValues.
  193. predictValueUseListOrder(Op, F, OM, Stack);
  194. }
  195. static UseListOrderStack predictUseListOrder(const Module *M) {
  196. OrderMap OM = orderModule(M);
  197. // Use-list orders need to be serialized after all the users have been added
  198. // to a value, or else the shuffles will be incomplete. Store them per
  199. // function in a stack.
  200. //
  201. // Aside from function order, the order of values doesn't matter much here.
  202. UseListOrderStack Stack;
  203. // We want to visit the functions backward now so we can list function-local
  204. // constants in the last Function they're used in. Module-level constants
  205. // have already been visited above.
  206. for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
  207. const Function &F = *I;
  208. if (F.isDeclaration())
  209. continue;
  210. for (const BasicBlock &BB : F)
  211. predictValueUseListOrder(&BB, &F, OM, Stack);
  212. for (const Argument &A : F.args())
  213. predictValueUseListOrder(&A, &F, OM, Stack);
  214. for (const BasicBlock &BB : F)
  215. for (const Instruction &I : BB)
  216. for (const Value *Op : I.operands())
  217. if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
  218. predictValueUseListOrder(Op, &F, OM, Stack);
  219. for (const BasicBlock &BB : F)
  220. for (const Instruction &I : BB)
  221. predictValueUseListOrder(&I, &F, OM, Stack);
  222. }
  223. // Visit globals last.
  224. for (const GlobalVariable &G : M->globals())
  225. predictValueUseListOrder(&G, nullptr, OM, Stack);
  226. for (const Function &F : *M)
  227. predictValueUseListOrder(&F, nullptr, OM, Stack);
  228. for (const GlobalAlias &A : M->aliases())
  229. predictValueUseListOrder(&A, nullptr, OM, Stack);
  230. for (const GlobalVariable &G : M->globals())
  231. if (G.hasInitializer())
  232. predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
  233. for (const GlobalAlias &A : M->aliases())
  234. predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
  235. for (const Function &F : *M)
  236. if (F.hasPrefixData())
  237. predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
  238. return Stack;
  239. }
  240. static const Module *getModuleFromVal(const Value *V) {
  241. if (const Argument *MA = dyn_cast<Argument>(V))
  242. return MA->getParent() ? MA->getParent()->getParent() : nullptr;
  243. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  244. return BB->getParent() ? BB->getParent()->getParent() : nullptr;
  245. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  246. const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
  247. return M ? M->getParent() : nullptr;
  248. }
  249. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  250. return GV->getParent();
  251. if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
  252. for (const User *U : MAV->users())
  253. if (isa<Instruction>(U))
  254. if (const Module *M = getModuleFromVal(U))
  255. return M;
  256. return nullptr;
  257. }
  258. return nullptr;
  259. }
  260. static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
  261. switch (cc) {
  262. default: Out << "cc" << cc; break;
  263. case CallingConv::Fast: Out << "fastcc"; break;
  264. case CallingConv::Cold: Out << "coldcc"; break;
  265. case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
  266. case CallingConv::AnyReg: Out << "anyregcc"; break;
  267. case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
  268. case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
  269. case CallingConv::GHC: Out << "ghccc"; break;
  270. case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
  271. case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
  272. case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
  273. case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
  274. case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
  275. case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
  276. case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
  277. case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
  278. case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
  279. case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
  280. case CallingConv::PTX_Device: Out << "ptx_device"; break;
  281. case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
  282. case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
  283. case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
  284. case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
  285. }
  286. }
  287. // PrintEscapedString - Print each character of the specified string, escaping
  288. // it if it is not printable or if it is an escape char.
  289. static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
  290. for (unsigned i = 0, e = Name.size(); i != e; ++i) {
  291. unsigned char C = Name[i];
  292. if (isprint(C) && C != '\\' && C != '"')
  293. Out << C;
  294. else
  295. Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  296. }
  297. }
  298. enum PrefixType {
  299. GlobalPrefix,
  300. ComdatPrefix,
  301. LabelPrefix,
  302. LocalPrefix,
  303. NoPrefix
  304. };
  305. /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
  306. /// prefixed with % (if the string only contains simple characters) or is
  307. /// surrounded with ""'s (if it has special chars in it). Print it out.
  308. static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
  309. assert(!Name.empty() && "Cannot get empty name!");
  310. switch (Prefix) {
  311. case NoPrefix: break;
  312. case GlobalPrefix: OS << '@'; break;
  313. case ComdatPrefix: OS << '$'; break;
  314. case LabelPrefix: break;
  315. case LocalPrefix: OS << '%'; break;
  316. }
  317. // Scan the name to see if it needs quotes first.
  318. bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
  319. if (!NeedsQuotes) {
  320. for (unsigned i = 0, e = Name.size(); i != e; ++i) {
  321. // By making this unsigned, the value passed in to isalnum will always be
  322. // in the range 0-255. This is important when building with MSVC because
  323. // its implementation will assert. This situation can arise when dealing
  324. // with UTF-8 multibyte characters.
  325. unsigned char C = Name[i];
  326. if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
  327. C != '_') {
  328. NeedsQuotes = true;
  329. break;
  330. }
  331. }
  332. }
  333. // If we didn't need any quotes, just write out the name in one blast.
  334. if (!NeedsQuotes) {
  335. OS << Name;
  336. return;
  337. }
  338. // Okay, we need quotes. Output the quotes and escape any scary characters as
  339. // needed.
  340. OS << '"';
  341. PrintEscapedString(Name, OS);
  342. OS << '"';
  343. }
  344. /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
  345. /// prefixed with % (if the string only contains simple characters) or is
  346. /// surrounded with ""'s (if it has special chars in it). Print it out.
  347. static void PrintLLVMName(raw_ostream &OS, const Value *V) {
  348. PrintLLVMName(OS, V->getName(),
  349. isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
  350. }
  351. namespace {
  352. class TypePrinting {
  353. TypePrinting(const TypePrinting &) = delete;
  354. void operator=(const TypePrinting&) = delete;
  355. public:
  356. /// NamedTypes - The named types that are used by the current module.
  357. TypeFinder NamedTypes;
  358. /// NumberedTypes - The numbered types, along with their value.
  359. DenseMap<StructType*, unsigned> NumberedTypes;
  360. TypePrinting() = default;
  361. void incorporateTypes(const Module &M);
  362. void print(Type *Ty, raw_ostream &OS);
  363. void printStructBody(StructType *Ty, raw_ostream &OS);
  364. };
  365. } // namespace
  366. void TypePrinting::incorporateTypes(const Module &M) {
  367. NamedTypes.run(M, false);
  368. // The list of struct types we got back includes all the struct types, split
  369. // the unnamed ones out to a numbering and remove the anonymous structs.
  370. unsigned NextNumber = 0;
  371. std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
  372. for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
  373. StructType *STy = *I;
  374. // Ignore anonymous types.
  375. if (STy->isLiteral())
  376. continue;
  377. if (STy->getName().empty())
  378. NumberedTypes[STy] = NextNumber++;
  379. else
  380. *NextToUse++ = STy;
  381. }
  382. NamedTypes.erase(NextToUse, NamedTypes.end());
  383. }
  384. /// CalcTypeName - Write the specified type to the specified raw_ostream, making
  385. /// use of type names or up references to shorten the type name where possible.
  386. void TypePrinting::print(Type *Ty, raw_ostream &OS) {
  387. switch (Ty->getTypeID()) {
  388. case Type::VoidTyID: OS << "void"; return;
  389. case Type::HalfTyID: OS << "half"; return;
  390. case Type::FloatTyID: OS << "float"; return;
  391. case Type::DoubleTyID: OS << "double"; return;
  392. case Type::X86_FP80TyID: OS << "x86_fp80"; return;
  393. case Type::FP128TyID: OS << "fp128"; return;
  394. case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
  395. case Type::LabelTyID: OS << "label"; return;
  396. case Type::MetadataTyID: OS << "metadata"; return;
  397. case Type::X86_MMXTyID: OS << "x86_mmx"; return;
  398. case Type::IntegerTyID:
  399. OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
  400. return;
  401. case Type::FunctionTyID: {
  402. FunctionType *FTy = cast<FunctionType>(Ty);
  403. print(FTy->getReturnType(), OS);
  404. OS << " (";
  405. for (FunctionType::param_iterator I = FTy->param_begin(),
  406. E = FTy->param_end(); I != E; ++I) {
  407. if (I != FTy->param_begin())
  408. OS << ", ";
  409. print(*I, OS);
  410. }
  411. if (FTy->isVarArg()) {
  412. if (FTy->getNumParams()) OS << ", ";
  413. OS << "...";
  414. }
  415. OS << ')';
  416. return;
  417. }
  418. case Type::StructTyID: {
  419. StructType *STy = cast<StructType>(Ty);
  420. if (STy->isLiteral())
  421. return printStructBody(STy, OS);
  422. if (!STy->getName().empty())
  423. return PrintLLVMName(OS, STy->getName(), LocalPrefix);
  424. DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
  425. if (I != NumberedTypes.end())
  426. OS << '%' << I->second;
  427. else // Not enumerated, print the hex address.
  428. OS << "%\"type " << STy << '\"';
  429. return;
  430. }
  431. case Type::PointerTyID: {
  432. PointerType *PTy = cast<PointerType>(Ty);
  433. print(PTy->getElementType(), OS);
  434. if (unsigned AddressSpace = PTy->getAddressSpace())
  435. OS << " addrspace(" << AddressSpace << ')';
  436. OS << '*';
  437. return;
  438. }
  439. case Type::ArrayTyID: {
  440. ArrayType *ATy = cast<ArrayType>(Ty);
  441. OS << '[' << ATy->getNumElements() << " x ";
  442. print(ATy->getElementType(), OS);
  443. OS << ']';
  444. return;
  445. }
  446. case Type::VectorTyID: {
  447. VectorType *PTy = cast<VectorType>(Ty);
  448. OS << "<" << PTy->getNumElements() << " x ";
  449. print(PTy->getElementType(), OS);
  450. OS << '>';
  451. return;
  452. }
  453. }
  454. llvm_unreachable("Invalid TypeID");
  455. }
  456. void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
  457. if (STy->isOpaque()) {
  458. OS << "opaque";
  459. return;
  460. }
  461. if (STy->isPacked())
  462. OS << '<';
  463. if (STy->getNumElements() == 0) {
  464. OS << "{}";
  465. } else {
  466. StructType::element_iterator I = STy->element_begin();
  467. OS << "{ ";
  468. print(*I++, OS);
  469. for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
  470. OS << ", ";
  471. print(*I, OS);
  472. }
  473. OS << " }";
  474. }
  475. if (STy->isPacked())
  476. OS << '>';
  477. }
  478. namespace llvm {
  479. //===----------------------------------------------------------------------===//
  480. // SlotTracker Class: Enumerate slot numbers for unnamed values
  481. //===----------------------------------------------------------------------===//
  482. /// This class provides computation of slot numbers for LLVM Assembly writing.
  483. ///
  484. class SlotTracker {
  485. public:
  486. /// ValueMap - A mapping of Values to slot numbers.
  487. typedef DenseMap<const Value*, unsigned> ValueMap;
  488. private:
  489. /// TheModule - The module for which we are holding slot numbers.
  490. const Module* TheModule;
  491. /// TheFunction - The function for which we are holding slot numbers.
  492. const Function* TheFunction;
  493. bool FunctionProcessed;
  494. bool ShouldInitializeAllMetadata;
  495. /// mMap - The slot map for the module level data.
  496. ValueMap mMap;
  497. unsigned mNext;
  498. /// fMap - The slot map for the function level data.
  499. ValueMap fMap;
  500. unsigned fNext;
  501. /// mdnMap - Map for MDNodes.
  502. DenseMap<const MDNode*, unsigned> mdnMap;
  503. unsigned mdnNext;
  504. /// asMap - The slot map for attribute sets.
  505. DenseMap<AttributeSet, unsigned> asMap;
  506. unsigned asNext;
  507. public:
  508. /// Construct from a module.
  509. ///
  510. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  511. /// functions, giving correct numbering for metadata referenced only from
  512. /// within a function (even if no functions have been initialized).
  513. explicit SlotTracker(const Module *M,
  514. bool ShouldInitializeAllMetadata = false);
  515. /// Construct from a function, starting out in incorp state.
  516. ///
  517. /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
  518. /// functions, giving correct numbering for metadata referenced only from
  519. /// within a function (even if no functions have been initialized).
  520. explicit SlotTracker(const Function *F,
  521. bool ShouldInitializeAllMetadata = false);
  522. /// Return the slot number of the specified value in it's type
  523. /// plane. If something is not in the SlotTracker, return -1.
  524. int getLocalSlot(const Value *V);
  525. int getGlobalSlot(const GlobalValue *V);
  526. int getMetadataSlot(const MDNode *N);
  527. int getAttributeGroupSlot(AttributeSet AS);
  528. /// If you'd like to deal with a function instead of just a module, use
  529. /// this method to get its data into the SlotTracker.
  530. void incorporateFunction(const Function *F) {
  531. TheFunction = F;
  532. FunctionProcessed = false;
  533. }
  534. const Function *getFunction() const { return TheFunction; }
  535. /// After calling incorporateFunction, use this method to remove the
  536. /// most recently incorporated function from the SlotTracker. This
  537. /// will reset the state of the machine back to just the module contents.
  538. void purgeFunction();
  539. /// MDNode map iterators.
  540. typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
  541. mdn_iterator mdn_begin() { return mdnMap.begin(); }
  542. mdn_iterator mdn_end() { return mdnMap.end(); }
  543. unsigned mdn_size() const { return mdnMap.size(); }
  544. bool mdn_empty() const { return mdnMap.empty(); }
  545. /// AttributeSet map iterators.
  546. typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
  547. as_iterator as_begin() { return asMap.begin(); }
  548. as_iterator as_end() { return asMap.end(); }
  549. unsigned as_size() const { return asMap.size(); }
  550. bool as_empty() const { return asMap.empty(); }
  551. /// This function does the actual initialization.
  552. inline void initialize();
  553. // Implementation Details
  554. private:
  555. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  556. void CreateModuleSlot(const GlobalValue *V);
  557. /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
  558. void CreateMetadataSlot(const MDNode *N);
  559. /// CreateFunctionSlot - Insert the specified Value* into the slot table.
  560. void CreateFunctionSlot(const Value *V);
  561. /// \brief Insert the specified AttributeSet into the slot table.
  562. void CreateAttributeSetSlot(AttributeSet AS);
  563. /// Add all of the module level global variables (and their initializers)
  564. /// and function declarations, but not the contents of those functions.
  565. void processModule();
  566. /// Add all of the functions arguments, basic blocks, and instructions.
  567. void processFunction();
  568. /// Add all of the metadata from a function.
  569. void processFunctionMetadata(const Function &F);
  570. /// Add all of the metadata from an instruction.
  571. void processInstructionMetadata(const Instruction &I);
  572. SlotTracker(const SlotTracker &) = delete;
  573. void operator=(const SlotTracker &) = delete;
  574. };
  575. } // namespace llvm
  576. ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
  577. const Function *F)
  578. : M(M), F(F), Machine(&Machine) {}
  579. ModuleSlotTracker::ModuleSlotTracker(const Module *M,
  580. bool ShouldInitializeAllMetadata)
  581. : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
  582. : nullptr),
  583. M(M), Machine(MachineStorage.get()) {}
  584. ModuleSlotTracker::~ModuleSlotTracker() {}
  585. void ModuleSlotTracker::incorporateFunction(const Function &F) {
  586. if (!Machine)
  587. return;
  588. // Nothing to do if this is the right function already.
  589. if (this->F == &F)
  590. return;
  591. if (this->F)
  592. Machine->purgeFunction();
  593. Machine->incorporateFunction(&F);
  594. this->F = &F;
  595. }
  596. #if 0 // HLSL Change - Unused
  597. static SlotTracker *createSlotTracker(const Module *M) {
  598. return new SlotTracker(M);
  599. }
  600. #endif
  601. static SlotTracker *createSlotTracker(const Value *V) {
  602. if (const Argument *FA = dyn_cast<Argument>(V))
  603. return new SlotTracker(FA->getParent());
  604. if (const Instruction *I = dyn_cast<Instruction>(V))
  605. if (I->getParent())
  606. return new SlotTracker(I->getParent()->getParent());
  607. if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
  608. return new SlotTracker(BB->getParent());
  609. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
  610. return new SlotTracker(GV->getParent());
  611. if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
  612. return new SlotTracker(GA->getParent());
  613. if (const Function *Func = dyn_cast<Function>(V))
  614. return new SlotTracker(Func);
  615. return nullptr;
  616. }
  617. #if 0
  618. #define ST_DEBUG(X) dbgs() << X
  619. #else
  620. #define ST_DEBUG(X)
  621. #endif
  622. // Module level constructor. Causes the contents of the Module (sans functions)
  623. // to be added to the slot table.
  624. SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
  625. : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
  626. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
  627. fNext(0), mdnNext(0), asNext(0) {}
  628. // Function level constructor. Causes the contents of the Module and the one
  629. // function provided to be added to the slot table.
  630. SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
  631. : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
  632. FunctionProcessed(false),
  633. ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
  634. fNext(0), mdnNext(0), asNext(0) {}
  635. inline void SlotTracker::initialize() {
  636. if (TheModule) {
  637. processModule();
  638. TheModule = nullptr; ///< Prevent re-processing next time we're called.
  639. }
  640. if (TheFunction && !FunctionProcessed)
  641. processFunction();
  642. }
  643. // Iterate through all the global variables, functions, and global
  644. // variable initializers and create slots for them.
  645. void SlotTracker::processModule() {
  646. ST_DEBUG("begin processModule!\n");
  647. // Add all of the unnamed global variables to the value table.
  648. for (const GlobalVariable &Var : TheModule->globals()) {
  649. if (!Var.hasName())
  650. CreateModuleSlot(&Var);
  651. }
  652. for (const GlobalAlias &A : TheModule->aliases()) {
  653. if (!A.hasName())
  654. CreateModuleSlot(&A);
  655. }
  656. // Add metadata used by named metadata.
  657. for (const NamedMDNode &NMD : TheModule->named_metadata()) {
  658. for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
  659. CreateMetadataSlot(NMD.getOperand(i));
  660. }
  661. for (const Function &F : *TheModule) {
  662. if (!F.hasName())
  663. // Add all the unnamed functions to the table.
  664. CreateModuleSlot(&F);
  665. if (ShouldInitializeAllMetadata)
  666. processFunctionMetadata(F);
  667. // Add all the function attributes to the table.
  668. // FIXME: Add attributes of other objects?
  669. AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
  670. if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
  671. CreateAttributeSetSlot(FnAttrs);
  672. }
  673. ST_DEBUG("end processModule!\n");
  674. }
  675. // Process the arguments, basic blocks, and instructions of a function.
  676. void SlotTracker::processFunction() {
  677. ST_DEBUG("begin processFunction!\n");
  678. fNext = 0;
  679. // Add all the function arguments with no names.
  680. for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
  681. AE = TheFunction->arg_end(); AI != AE; ++AI)
  682. if (!AI->hasName())
  683. CreateFunctionSlot(AI);
  684. ST_DEBUG("Inserting Instructions:\n");
  685. // Add all of the basic blocks and instructions with no names.
  686. for (auto &BB : *TheFunction) {
  687. if (!BB.hasName())
  688. CreateFunctionSlot(&BB);
  689. processFunctionMetadata(*TheFunction);
  690. for (auto &I : BB) {
  691. if (!I.getType()->isVoidTy() && !I.hasName())
  692. CreateFunctionSlot(&I);
  693. // We allow direct calls to any llvm.foo function here, because the
  694. // target may not be linked into the optimizer.
  695. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  696. // Add all the call attributes to the table.
  697. AttributeSet Attrs = CI->getAttributes().getFnAttributes();
  698. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  699. CreateAttributeSetSlot(Attrs);
  700. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
  701. // Add all the call attributes to the table.
  702. AttributeSet Attrs = II->getAttributes().getFnAttributes();
  703. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  704. CreateAttributeSetSlot(Attrs);
  705. }
  706. }
  707. }
  708. FunctionProcessed = true;
  709. ST_DEBUG("end processFunction!\n");
  710. }
  711. void SlotTracker::processFunctionMetadata(const Function &F) {
  712. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  713. for (auto &BB : F) {
  714. F.getAllMetadata(MDs);
  715. for (auto &MD : MDs)
  716. CreateMetadataSlot(MD.second);
  717. for (auto &I : BB)
  718. processInstructionMetadata(I);
  719. }
  720. }
  721. void SlotTracker::processInstructionMetadata(const Instruction &I) {
  722. // Process metadata used directly by intrinsics.
  723. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  724. if (Function *F = CI->getCalledFunction())
  725. if (F->isIntrinsic())
  726. for (auto &Op : I.operands())
  727. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  728. if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
  729. CreateMetadataSlot(N);
  730. // Process metadata attached to this instruction.
  731. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  732. I.getAllMetadata(MDs);
  733. for (auto &MD : MDs)
  734. CreateMetadataSlot(MD.second);
  735. }
  736. /// Clean up after incorporating a function. This is the only way to get out of
  737. /// the function incorporation state that affects get*Slot/Create*Slot. Function
  738. /// incorporation state is indicated by TheFunction != 0.
  739. void SlotTracker::purgeFunction() {
  740. ST_DEBUG("begin purgeFunction!\n");
  741. fMap.clear(); // Simply discard the function level map
  742. TheFunction = nullptr;
  743. FunctionProcessed = false;
  744. ST_DEBUG("end purgeFunction!\n");
  745. }
  746. /// getGlobalSlot - Get the slot number of a global value.
  747. int SlotTracker::getGlobalSlot(const GlobalValue *V) {
  748. // Check for uninitialized state and do lazy initialization.
  749. initialize();
  750. // Find the value in the module map
  751. ValueMap::iterator MI = mMap.find(V);
  752. return MI == mMap.end() ? -1 : (int)MI->second;
  753. }
  754. /// getMetadataSlot - Get the slot number of a MDNode.
  755. int SlotTracker::getMetadataSlot(const MDNode *N) {
  756. // Check for uninitialized state and do lazy initialization.
  757. initialize();
  758. // Find the MDNode in the module map
  759. mdn_iterator MI = mdnMap.find(N);
  760. return MI == mdnMap.end() ? -1 : (int)MI->second;
  761. }
  762. /// getLocalSlot - Get the slot number for a value that is local to a function.
  763. int SlotTracker::getLocalSlot(const Value *V) {
  764. assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
  765. // Check for uninitialized state and do lazy initialization.
  766. initialize();
  767. ValueMap::iterator FI = fMap.find(V);
  768. return FI == fMap.end() ? -1 : (int)FI->second;
  769. }
  770. int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
  771. // Check for uninitialized state and do lazy initialization.
  772. initialize();
  773. // Find the AttributeSet in the module map.
  774. as_iterator AI = asMap.find(AS);
  775. return AI == asMap.end() ? -1 : (int)AI->second;
  776. }
  777. /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
  778. void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
  779. assert(V && "Can't insert a null Value into SlotTracker!");
  780. assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
  781. assert(!V->hasName() && "Doesn't need a slot!");
  782. unsigned DestSlot = mNext++;
  783. mMap[V] = DestSlot;
  784. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  785. DestSlot << " [");
  786. // G = Global, F = Function, A = Alias, o = other
  787. ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
  788. (isa<Function>(V) ? 'F' :
  789. (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
  790. }
  791. /// CreateSlot - Create a new slot for the specified value if it has no name.
  792. void SlotTracker::CreateFunctionSlot(const Value *V) {
  793. assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
  794. unsigned DestSlot = fNext++;
  795. fMap[V] = DestSlot;
  796. // G = Global, F = Function, o = other
  797. ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
  798. DestSlot << " [o]\n");
  799. }
  800. /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
  801. void SlotTracker::CreateMetadataSlot(const MDNode *N) {
  802. assert(N && "Can't insert a null Value into SlotTracker!");
  803. unsigned DestSlot = mdnNext;
  804. if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
  805. return;
  806. ++mdnNext;
  807. // Recursively add any MDNodes referenced by operands.
  808. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  809. if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
  810. CreateMetadataSlot(Op);
  811. }
  812. void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
  813. assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
  814. "Doesn't need a slot!");
  815. as_iterator I = asMap.find(AS);
  816. if (I != asMap.end())
  817. return;
  818. unsigned DestSlot = asNext++;
  819. asMap[AS] = DestSlot;
  820. }
  821. //===----------------------------------------------------------------------===//
  822. // AsmWriter Implementation
  823. //===----------------------------------------------------------------------===//
  824. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  825. TypePrinting *TypePrinter,
  826. SlotTracker *Machine,
  827. const Module *Context);
  828. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  829. TypePrinting *TypePrinter,
  830. SlotTracker *Machine, const Module *Context,
  831. bool FromValue = false);
  832. static const char *getPredicateText(unsigned predicate) {
  833. const char * pred = "unknown";
  834. switch (predicate) {
  835. case FCmpInst::FCMP_FALSE: pred = "false"; break;
  836. case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
  837. case FCmpInst::FCMP_OGT: pred = "ogt"; break;
  838. case FCmpInst::FCMP_OGE: pred = "oge"; break;
  839. case FCmpInst::FCMP_OLT: pred = "olt"; break;
  840. case FCmpInst::FCMP_OLE: pred = "ole"; break;
  841. case FCmpInst::FCMP_ONE: pred = "one"; break;
  842. case FCmpInst::FCMP_ORD: pred = "ord"; break;
  843. case FCmpInst::FCMP_UNO: pred = "uno"; break;
  844. case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
  845. case FCmpInst::FCMP_UGT: pred = "ugt"; break;
  846. case FCmpInst::FCMP_UGE: pred = "uge"; break;
  847. case FCmpInst::FCMP_ULT: pred = "ult"; break;
  848. case FCmpInst::FCMP_ULE: pred = "ule"; break;
  849. case FCmpInst::FCMP_UNE: pred = "une"; break;
  850. case FCmpInst::FCMP_TRUE: pred = "true"; break;
  851. case ICmpInst::ICMP_EQ: pred = "eq"; break;
  852. case ICmpInst::ICMP_NE: pred = "ne"; break;
  853. case ICmpInst::ICMP_SGT: pred = "sgt"; break;
  854. case ICmpInst::ICMP_SGE: pred = "sge"; break;
  855. case ICmpInst::ICMP_SLT: pred = "slt"; break;
  856. case ICmpInst::ICMP_SLE: pred = "sle"; break;
  857. case ICmpInst::ICMP_UGT: pred = "ugt"; break;
  858. case ICmpInst::ICMP_UGE: pred = "uge"; break;
  859. case ICmpInst::ICMP_ULT: pred = "ult"; break;
  860. case ICmpInst::ICMP_ULE: pred = "ule"; break;
  861. }
  862. return pred;
  863. }
  864. static void writeAtomicRMWOperation(raw_ostream &Out,
  865. AtomicRMWInst::BinOp Op) {
  866. switch (Op) {
  867. default: Out << " <unknown operation " << Op << ">"; break;
  868. case AtomicRMWInst::Xchg: Out << " xchg"; break;
  869. case AtomicRMWInst::Add: Out << " add"; break;
  870. case AtomicRMWInst::Sub: Out << " sub"; break;
  871. case AtomicRMWInst::And: Out << " and"; break;
  872. case AtomicRMWInst::Nand: Out << " nand"; break;
  873. case AtomicRMWInst::Or: Out << " or"; break;
  874. case AtomicRMWInst::Xor: Out << " xor"; break;
  875. case AtomicRMWInst::Max: Out << " max"; break;
  876. case AtomicRMWInst::Min: Out << " min"; break;
  877. case AtomicRMWInst::UMax: Out << " umax"; break;
  878. case AtomicRMWInst::UMin: Out << " umin"; break;
  879. }
  880. }
  881. static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
  882. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(U)) {
  883. // Unsafe algebra implies all the others, no need to write them all out
  884. if (FPOp->hasUnsafeAlgebra())
  885. Out << " fast";
  886. else {
  887. if (FPOp->hasNoNaNs())
  888. Out << " nnan";
  889. if (FPOp->hasNoInfs())
  890. Out << " ninf";
  891. if (FPOp->hasNoSignedZeros())
  892. Out << " nsz";
  893. if (FPOp->hasAllowReciprocal())
  894. Out << " arcp";
  895. }
  896. }
  897. if (const OverflowingBinaryOperator *OBO =
  898. dyn_cast<OverflowingBinaryOperator>(U)) {
  899. if (OBO->hasNoUnsignedWrap())
  900. Out << " nuw";
  901. if (OBO->hasNoSignedWrap())
  902. Out << " nsw";
  903. } else if (const PossiblyExactOperator *Div =
  904. dyn_cast<PossiblyExactOperator>(U)) {
  905. if (Div->isExact())
  906. Out << " exact";
  907. } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  908. if (GEP->isInBounds())
  909. Out << " inbounds";
  910. }
  911. }
  912. static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
  913. TypePrinting &TypePrinter,
  914. SlotTracker *Machine,
  915. const Module *Context) {
  916. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  917. if (CI->getType()->isIntegerTy(1)) {
  918. Out << (CI->getZExtValue() ? "true" : "false");
  919. return;
  920. }
  921. Out << CI->getValue();
  922. return;
  923. }
  924. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  925. if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
  926. &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
  927. // We would like to output the FP constant value in exponential notation,
  928. // but we cannot do this if doing so will lose precision. Check here to
  929. // make sure that we only output it in exponential format if we can parse
  930. // the value back and get the same value.
  931. //
  932. bool ignored;
  933. bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
  934. bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
  935. bool isInf = CFP->getValueAPF().isInfinity();
  936. bool isNaN = CFP->getValueAPF().isNaN();
  937. if (!isHalf && !isInf && !isNaN) {
  938. double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
  939. CFP->getValueAPF().convertToFloat();
  940. SmallString<128> StrVal;
  941. raw_svector_ostream(StrVal) << Val;
  942. // Check to make sure that the stringized number is not some string like
  943. // "Inf" or NaN, that atof will accept, but the lexer will not. Check
  944. // that the string matches the "[-+]?[0-9]" regex.
  945. //
  946. if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  947. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  948. (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
  949. // Reparse stringized version!
  950. if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
  951. Out << StrVal;
  952. return;
  953. }
  954. }
  955. }
  956. // Otherwise we could not reparse it to exactly the same value, so we must
  957. // output the string in hexadecimal format! Note that loading and storing
  958. // floating point types changes the bits of NaNs on some hosts, notably
  959. // x86, so we must not use these types.
  960. static_assert(sizeof(double) == sizeof(uint64_t),
  961. "assuming that double is 64 bits!");
  962. char Buffer[40];
  963. APFloat apf = CFP->getValueAPF();
  964. // Halves and floats are represented in ASCII IR as double, convert.
  965. if (!isDouble)
  966. apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
  967. &ignored);
  968. Out << "0x" <<
  969. utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
  970. Buffer+40);
  971. return;
  972. }
  973. // Either half, or some form of long double.
  974. // These appear as a magic letter identifying the type, then a
  975. // fixed number of hex digits.
  976. Out << "0x";
  977. // Bit position, in the current word, of the next nibble to print.
  978. int shiftcount;
  979. if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
  980. Out << 'K';
  981. // api needed to prevent premature destruction
  982. APInt api = CFP->getValueAPF().bitcastToAPInt();
  983. const uint64_t* p = api.getRawData();
  984. uint64_t word = p[1];
  985. shiftcount = 12;
  986. int width = api.getBitWidth();
  987. for (int j=0; j<width; j+=4, shiftcount-=4) {
  988. unsigned int nibble = (word>>shiftcount) & 15;
  989. if (nibble < 10)
  990. Out << (unsigned char)(nibble + '0');
  991. else
  992. Out << (unsigned char)(nibble - 10 + 'A');
  993. if (shiftcount == 0 && j+4 < width) {
  994. word = *p;
  995. shiftcount = 64;
  996. if (width-j-4 < 64)
  997. shiftcount = width-j-4;
  998. }
  999. }
  1000. return;
  1001. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
  1002. shiftcount = 60;
  1003. Out << 'L';
  1004. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
  1005. shiftcount = 60;
  1006. Out << 'M';
  1007. } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
  1008. shiftcount = 12;
  1009. Out << 'H';
  1010. } else
  1011. llvm_unreachable("Unsupported floating point type");
  1012. // api needed to prevent premature destruction
  1013. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1014. const uint64_t* p = api.getRawData();
  1015. uint64_t word = *p;
  1016. int width = api.getBitWidth();
  1017. for (int j=0; j<width; j+=4, shiftcount-=4) {
  1018. unsigned int nibble = (word>>shiftcount) & 15;
  1019. if (nibble < 10)
  1020. Out << (unsigned char)(nibble + '0');
  1021. else
  1022. Out << (unsigned char)(nibble - 10 + 'A');
  1023. if (shiftcount == 0 && j+4 < width) {
  1024. word = *(++p);
  1025. shiftcount = 64;
  1026. if (width-j-4 < 64)
  1027. shiftcount = width-j-4;
  1028. }
  1029. }
  1030. return;
  1031. }
  1032. if (isa<ConstantAggregateZero>(CV)) {
  1033. Out << "zeroinitializer";
  1034. return;
  1035. }
  1036. if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
  1037. Out << "blockaddress(";
  1038. WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
  1039. Context);
  1040. Out << ", ";
  1041. WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
  1042. Context);
  1043. Out << ")";
  1044. return;
  1045. }
  1046. if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
  1047. Type *ETy = CA->getType()->getElementType();
  1048. Out << '[';
  1049. TypePrinter.print(ETy, Out);
  1050. Out << ' ';
  1051. WriteAsOperandInternal(Out, CA->getOperand(0),
  1052. &TypePrinter, Machine,
  1053. Context);
  1054. for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
  1055. Out << ", ";
  1056. TypePrinter.print(ETy, Out);
  1057. Out << ' ';
  1058. WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
  1059. Context);
  1060. }
  1061. Out << ']';
  1062. return;
  1063. }
  1064. if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
  1065. // As a special case, print the array as a string if it is an array of
  1066. // i8 with ConstantInt values.
  1067. if (CA->isString()) {
  1068. Out << "c\"";
  1069. PrintEscapedString(CA->getAsString(), Out);
  1070. Out << '"';
  1071. return;
  1072. }
  1073. Type *ETy = CA->getType()->getElementType();
  1074. Out << '[';
  1075. TypePrinter.print(ETy, Out);
  1076. Out << ' ';
  1077. WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
  1078. &TypePrinter, Machine,
  1079. Context);
  1080. for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
  1081. Out << ", ";
  1082. TypePrinter.print(ETy, Out);
  1083. Out << ' ';
  1084. WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
  1085. Machine, Context);
  1086. }
  1087. Out << ']';
  1088. return;
  1089. }
  1090. if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
  1091. if (CS->getType()->isPacked())
  1092. Out << '<';
  1093. Out << '{';
  1094. unsigned N = CS->getNumOperands();
  1095. if (N) {
  1096. Out << ' ';
  1097. TypePrinter.print(CS->getOperand(0)->getType(), Out);
  1098. Out << ' ';
  1099. WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
  1100. Context);
  1101. for (unsigned i = 1; i < N; i++) {
  1102. Out << ", ";
  1103. TypePrinter.print(CS->getOperand(i)->getType(), Out);
  1104. Out << ' ';
  1105. WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
  1106. Context);
  1107. }
  1108. Out << ' ';
  1109. }
  1110. Out << '}';
  1111. if (CS->getType()->isPacked())
  1112. Out << '>';
  1113. return;
  1114. }
  1115. if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
  1116. Type *ETy = CV->getType()->getVectorElementType();
  1117. Out << '<';
  1118. TypePrinter.print(ETy, Out);
  1119. Out << ' ';
  1120. WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
  1121. Machine, Context);
  1122. for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
  1123. Out << ", ";
  1124. TypePrinter.print(ETy, Out);
  1125. Out << ' ';
  1126. WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
  1127. Machine, Context);
  1128. }
  1129. Out << '>';
  1130. return;
  1131. }
  1132. if (isa<ConstantPointerNull>(CV)) {
  1133. Out << "null";
  1134. return;
  1135. }
  1136. if (isa<UndefValue>(CV)) {
  1137. Out << "undef";
  1138. return;
  1139. }
  1140. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  1141. Out << CE->getOpcodeName();
  1142. WriteOptimizationInfo(Out, CE);
  1143. if (CE->isCompare())
  1144. Out << ' ' << getPredicateText(CE->getPredicate());
  1145. Out << " (";
  1146. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
  1147. TypePrinter.print(
  1148. cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
  1149. ->getElementType(),
  1150. Out);
  1151. Out << ", ";
  1152. }
  1153. for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
  1154. TypePrinter.print((*OI)->getType(), Out);
  1155. Out << ' ';
  1156. WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
  1157. if (OI+1 != CE->op_end())
  1158. Out << ", ";
  1159. }
  1160. if (CE->hasIndices()) {
  1161. ArrayRef<unsigned> Indices = CE->getIndices();
  1162. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  1163. Out << ", " << Indices[i];
  1164. }
  1165. if (CE->isCast()) {
  1166. Out << " to ";
  1167. TypePrinter.print(CE->getType(), Out);
  1168. }
  1169. Out << ')';
  1170. return;
  1171. }
  1172. Out << "<placeholder or erroneous Constant>";
  1173. }
  1174. static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
  1175. TypePrinting *TypePrinter, SlotTracker *Machine,
  1176. const Module *Context) {
  1177. Out << "!{";
  1178. for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
  1179. const Metadata *MD = Node->getOperand(mi);
  1180. if (!MD)
  1181. Out << "null";
  1182. else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
  1183. Value *V = MDV->getValue();
  1184. TypePrinter->print(V->getType(), Out);
  1185. Out << ' ';
  1186. WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
  1187. } else {
  1188. WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
  1189. }
  1190. if (mi + 1 != me)
  1191. Out << ", ";
  1192. }
  1193. Out << "}";
  1194. }
  1195. namespace {
  1196. struct FieldSeparator {
  1197. bool Skip;
  1198. const char *Sep;
  1199. FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
  1200. };
  1201. raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
  1202. if (FS.Skip) {
  1203. FS.Skip = false;
  1204. return OS;
  1205. }
  1206. return OS << FS.Sep;
  1207. }
  1208. struct MDFieldPrinter {
  1209. raw_ostream &Out;
  1210. FieldSeparator FS;
  1211. TypePrinting *TypePrinter;
  1212. SlotTracker *Machine;
  1213. const Module *Context;
  1214. explicit MDFieldPrinter(raw_ostream &Out)
  1215. : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
  1216. MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
  1217. SlotTracker *Machine, const Module *Context)
  1218. : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
  1219. }
  1220. void printTag(const DINode *N);
  1221. void printString(StringRef Name, StringRef Value,
  1222. bool ShouldSkipEmpty = true);
  1223. void printMetadata(StringRef Name, const Metadata *MD,
  1224. bool ShouldSkipNull = true);
  1225. template <class IntTy>
  1226. void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
  1227. void printBool(StringRef Name, bool Value);
  1228. void printDIFlags(StringRef Name, unsigned Flags);
  1229. template <class IntTy, class Stringifier>
  1230. void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
  1231. bool ShouldSkipZero = true);
  1232. };
  1233. } // end namespace
  1234. void MDFieldPrinter::printTag(const DINode *N) {
  1235. Out << FS << "tag: ";
  1236. if (const char *Tag = dwarf::TagString(N->getTag()))
  1237. Out << Tag;
  1238. else
  1239. Out << N->getTag();
  1240. }
  1241. void MDFieldPrinter::printString(StringRef Name, StringRef Value,
  1242. bool ShouldSkipEmpty) {
  1243. if (ShouldSkipEmpty && Value.empty())
  1244. return;
  1245. Out << FS << Name << ": \"";
  1246. PrintEscapedString(Value, Out);
  1247. Out << "\"";
  1248. }
  1249. static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
  1250. TypePrinting *TypePrinter,
  1251. SlotTracker *Machine,
  1252. const Module *Context) {
  1253. if (!MD) {
  1254. Out << "null";
  1255. return;
  1256. }
  1257. WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
  1258. }
  1259. void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
  1260. bool ShouldSkipNull) {
  1261. if (ShouldSkipNull && !MD)
  1262. return;
  1263. Out << FS << Name << ": ";
  1264. writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
  1265. }
  1266. template <class IntTy>
  1267. void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
  1268. if (ShouldSkipZero && !Int)
  1269. return;
  1270. Out << FS << Name << ": " << Int;
  1271. }
  1272. void MDFieldPrinter::printBool(StringRef Name, bool Value) {
  1273. Out << FS << Name << ": " << (Value ? "true" : "false");
  1274. }
  1275. void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
  1276. if (!Flags)
  1277. return;
  1278. Out << FS << Name << ": ";
  1279. SmallVector<unsigned, 8> SplitFlags;
  1280. unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
  1281. FieldSeparator FlagsFS(" | ");
  1282. for (unsigned F : SplitFlags) {
  1283. const char *StringF = DINode::getFlagString(F);
  1284. assert(StringF && "Expected valid flag");
  1285. Out << FlagsFS << StringF;
  1286. }
  1287. if (Extra || SplitFlags.empty())
  1288. Out << FlagsFS << Extra;
  1289. }
  1290. template <class IntTy, class Stringifier>
  1291. void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
  1292. Stringifier toString, bool ShouldSkipZero) {
  1293. if (!Value)
  1294. return;
  1295. Out << FS << Name << ": ";
  1296. if (const char *S = toString(Value))
  1297. Out << S;
  1298. else
  1299. Out << Value;
  1300. }
  1301. static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
  1302. TypePrinting *TypePrinter, SlotTracker *Machine,
  1303. const Module *Context) {
  1304. Out << "!GenericDINode(";
  1305. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1306. Printer.printTag(N);
  1307. Printer.printString("header", N->getHeader());
  1308. if (N->getNumDwarfOperands()) {
  1309. Out << Printer.FS << "operands: {";
  1310. FieldSeparator IFS;
  1311. for (auto &I : N->dwarf_operands()) {
  1312. Out << IFS;
  1313. writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
  1314. }
  1315. Out << "}";
  1316. }
  1317. Out << ")";
  1318. }
  1319. static void writeDILocation(raw_ostream &Out, const DILocation *DL,
  1320. TypePrinting *TypePrinter, SlotTracker *Machine,
  1321. const Module *Context) {
  1322. Out << "!DILocation(";
  1323. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1324. // Always output the line, since 0 is a relevant and important value for it.
  1325. Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
  1326. Printer.printInt("column", DL->getColumn());
  1327. Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
  1328. Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
  1329. Out << ")";
  1330. }
  1331. static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
  1332. TypePrinting *, SlotTracker *, const Module *) {
  1333. Out << "!DISubrange(";
  1334. MDFieldPrinter Printer(Out);
  1335. Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
  1336. Printer.printInt("lowerBound", N->getLowerBound());
  1337. Out << ")";
  1338. }
  1339. static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
  1340. TypePrinting *, SlotTracker *, const Module *) {
  1341. Out << "!DIEnumerator(";
  1342. MDFieldPrinter Printer(Out);
  1343. Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
  1344. Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
  1345. Out << ")";
  1346. }
  1347. static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
  1348. TypePrinting *, SlotTracker *, const Module *) {
  1349. Out << "!DIBasicType(";
  1350. MDFieldPrinter Printer(Out);
  1351. if (N->getTag() != dwarf::DW_TAG_base_type)
  1352. Printer.printTag(N);
  1353. Printer.printString("name", N->getName());
  1354. Printer.printInt("size", N->getSizeInBits());
  1355. Printer.printInt("align", N->getAlignInBits());
  1356. Printer.printDwarfEnum("encoding", N->getEncoding(),
  1357. dwarf::AttributeEncodingString);
  1358. Out << ")";
  1359. }
  1360. static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
  1361. TypePrinting *TypePrinter, SlotTracker *Machine,
  1362. const Module *Context) {
  1363. Out << "!DIDerivedType(";
  1364. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1365. Printer.printTag(N);
  1366. Printer.printString("name", N->getName());
  1367. Printer.printMetadata("scope", N->getRawScope());
  1368. Printer.printMetadata("file", N->getRawFile());
  1369. Printer.printInt("line", N->getLine());
  1370. Printer.printMetadata("baseType", N->getRawBaseType(),
  1371. /* ShouldSkipNull */ false);
  1372. Printer.printInt("size", N->getSizeInBits());
  1373. Printer.printInt("align", N->getAlignInBits());
  1374. Printer.printInt("offset", N->getOffsetInBits());
  1375. Printer.printDIFlags("flags", N->getFlags());
  1376. Printer.printMetadata("extraData", N->getRawExtraData());
  1377. Out << ")";
  1378. }
  1379. static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
  1380. TypePrinting *TypePrinter,
  1381. SlotTracker *Machine, const Module *Context) {
  1382. Out << "!DICompositeType(";
  1383. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1384. Printer.printTag(N);
  1385. Printer.printString("name", N->getName());
  1386. Printer.printMetadata("scope", N->getRawScope());
  1387. Printer.printMetadata("file", N->getRawFile());
  1388. Printer.printInt("line", N->getLine());
  1389. Printer.printMetadata("baseType", N->getRawBaseType());
  1390. Printer.printInt("size", N->getSizeInBits());
  1391. Printer.printInt("align", N->getAlignInBits());
  1392. Printer.printInt("offset", N->getOffsetInBits());
  1393. Printer.printDIFlags("flags", N->getFlags());
  1394. Printer.printMetadata("elements", N->getRawElements());
  1395. Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
  1396. dwarf::LanguageString);
  1397. Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
  1398. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1399. Printer.printString("identifier", N->getIdentifier());
  1400. Out << ")";
  1401. }
  1402. static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
  1403. TypePrinting *TypePrinter,
  1404. SlotTracker *Machine, const Module *Context) {
  1405. Out << "!DISubroutineType(";
  1406. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1407. Printer.printDIFlags("flags", N->getFlags());
  1408. Printer.printMetadata("types", N->getRawTypeArray(),
  1409. /* ShouldSkipNull */ false);
  1410. Out << ")";
  1411. }
  1412. static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
  1413. SlotTracker *, const Module *) {
  1414. Out << "!DIFile(";
  1415. MDFieldPrinter Printer(Out);
  1416. Printer.printString("filename", N->getFilename(),
  1417. /* ShouldSkipEmpty */ false);
  1418. Printer.printString("directory", N->getDirectory(),
  1419. /* ShouldSkipEmpty */ false);
  1420. Out << ")";
  1421. }
  1422. static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
  1423. TypePrinting *TypePrinter, SlotTracker *Machine,
  1424. const Module *Context) {
  1425. Out << "!DICompileUnit(";
  1426. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1427. Printer.printDwarfEnum("language", N->getSourceLanguage(),
  1428. dwarf::LanguageString, /* ShouldSkipZero */ false);
  1429. Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
  1430. Printer.printString("producer", N->getProducer());
  1431. Printer.printBool("isOptimized", N->isOptimized());
  1432. Printer.printString("flags", N->getFlags());
  1433. Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
  1434. /* ShouldSkipZero */ false);
  1435. Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
  1436. Printer.printInt("emissionKind", N->getEmissionKind(),
  1437. /* ShouldSkipZero */ false);
  1438. Printer.printMetadata("enums", N->getRawEnumTypes());
  1439. Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
  1440. Printer.printMetadata("subprograms", N->getRawSubprograms());
  1441. Printer.printMetadata("globals", N->getRawGlobalVariables());
  1442. Printer.printMetadata("imports", N->getRawImportedEntities());
  1443. Printer.printInt("dwoId", N->getDWOId());
  1444. Out << ")";
  1445. }
  1446. static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
  1447. TypePrinting *TypePrinter, SlotTracker *Machine,
  1448. const Module *Context) {
  1449. Out << "!DISubprogram(";
  1450. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1451. Printer.printString("name", N->getName());
  1452. Printer.printString("linkageName", N->getLinkageName());
  1453. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1454. Printer.printMetadata("file", N->getRawFile());
  1455. Printer.printInt("line", N->getLine());
  1456. Printer.printMetadata("type", N->getRawType());
  1457. Printer.printBool("isLocal", N->isLocalToUnit());
  1458. Printer.printBool("isDefinition", N->isDefinition());
  1459. Printer.printInt("scopeLine", N->getScopeLine());
  1460. Printer.printMetadata("containingType", N->getRawContainingType());
  1461. Printer.printDwarfEnum("virtuality", N->getVirtuality(),
  1462. dwarf::VirtualityString);
  1463. Printer.printInt("virtualIndex", N->getVirtualIndex());
  1464. Printer.printDIFlags("flags", N->getFlags());
  1465. Printer.printBool("isOptimized", N->isOptimized());
  1466. Printer.printMetadata("function", N->getRawFunction());
  1467. Printer.printMetadata("templateParams", N->getRawTemplateParams());
  1468. Printer.printMetadata("declaration", N->getRawDeclaration());
  1469. Printer.printMetadata("variables", N->getRawVariables());
  1470. Out << ")";
  1471. }
  1472. static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
  1473. TypePrinting *TypePrinter, SlotTracker *Machine,
  1474. const Module *Context) {
  1475. Out << "!DILexicalBlock(";
  1476. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1477. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1478. Printer.printMetadata("file", N->getRawFile());
  1479. Printer.printInt("line", N->getLine());
  1480. Printer.printInt("column", N->getColumn());
  1481. Out << ")";
  1482. }
  1483. static void writeDILexicalBlockFile(raw_ostream &Out,
  1484. const DILexicalBlockFile *N,
  1485. TypePrinting *TypePrinter,
  1486. SlotTracker *Machine,
  1487. const Module *Context) {
  1488. Out << "!DILexicalBlockFile(";
  1489. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1490. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1491. Printer.printMetadata("file", N->getRawFile());
  1492. Printer.printInt("discriminator", N->getDiscriminator(),
  1493. /* ShouldSkipZero */ false);
  1494. Out << ")";
  1495. }
  1496. static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
  1497. TypePrinting *TypePrinter, SlotTracker *Machine,
  1498. const Module *Context) {
  1499. Out << "!DINamespace(";
  1500. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1501. Printer.printString("name", N->getName());
  1502. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1503. Printer.printMetadata("file", N->getRawFile());
  1504. Printer.printInt("line", N->getLine());
  1505. Out << ")";
  1506. }
  1507. static void writeDIModule(raw_ostream &Out, const DIModule *N,
  1508. TypePrinting *TypePrinter, SlotTracker *Machine,
  1509. const Module *Context) {
  1510. Out << "!DIModule(";
  1511. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1512. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1513. Printer.printString("name", N->getName());
  1514. Printer.printString("configMacros", N->getConfigurationMacros());
  1515. Printer.printString("includePath", N->getIncludePath());
  1516. Printer.printString("isysroot", N->getISysRoot());
  1517. Out << ")";
  1518. }
  1519. static void writeDITemplateTypeParameter(raw_ostream &Out,
  1520. const DITemplateTypeParameter *N,
  1521. TypePrinting *TypePrinter,
  1522. SlotTracker *Machine,
  1523. const Module *Context) {
  1524. Out << "!DITemplateTypeParameter(";
  1525. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1526. Printer.printString("name", N->getName());
  1527. Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
  1528. Out << ")";
  1529. }
  1530. static void writeDITemplateValueParameter(raw_ostream &Out,
  1531. const DITemplateValueParameter *N,
  1532. TypePrinting *TypePrinter,
  1533. SlotTracker *Machine,
  1534. const Module *Context) {
  1535. Out << "!DITemplateValueParameter(";
  1536. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1537. if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
  1538. Printer.printTag(N);
  1539. Printer.printString("name", N->getName());
  1540. Printer.printMetadata("type", N->getRawType());
  1541. Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
  1542. Out << ")";
  1543. }
  1544. static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
  1545. TypePrinting *TypePrinter,
  1546. SlotTracker *Machine, const Module *Context) {
  1547. Out << "!DIGlobalVariable(";
  1548. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1549. Printer.printString("name", N->getName());
  1550. Printer.printString("linkageName", N->getLinkageName());
  1551. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1552. Printer.printMetadata("file", N->getRawFile());
  1553. Printer.printInt("line", N->getLine());
  1554. Printer.printMetadata("type", N->getRawType());
  1555. Printer.printBool("isLocal", N->isLocalToUnit());
  1556. Printer.printBool("isDefinition", N->isDefinition());
  1557. Printer.printMetadata("variable", N->getRawVariable());
  1558. Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
  1559. Out << ")";
  1560. }
  1561. static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
  1562. TypePrinting *TypePrinter,
  1563. SlotTracker *Machine, const Module *Context) {
  1564. Out << "!DILocalVariable(";
  1565. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1566. Printer.printTag(N);
  1567. Printer.printString("name", N->getName());
  1568. Printer.printInt("arg", N->getArg(),
  1569. /* ShouldSkipZero */
  1570. N->getTag() == dwarf::DW_TAG_auto_variable);
  1571. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1572. Printer.printMetadata("file", N->getRawFile());
  1573. Printer.printInt("line", N->getLine());
  1574. Printer.printMetadata("type", N->getRawType());
  1575. Printer.printDIFlags("flags", N->getFlags());
  1576. Out << ")";
  1577. }
  1578. static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
  1579. TypePrinting *TypePrinter, SlotTracker *Machine,
  1580. const Module *Context) {
  1581. Out << "!DIExpression(";
  1582. FieldSeparator FS;
  1583. if (N->isValid()) {
  1584. for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
  1585. const char *OpStr = dwarf::OperationEncodingString(I->getOp());
  1586. assert(OpStr && "Expected valid opcode");
  1587. Out << FS << OpStr;
  1588. for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
  1589. Out << FS << I->getArg(A);
  1590. }
  1591. } else {
  1592. for (const auto &I : N->getElements())
  1593. Out << FS << I;
  1594. }
  1595. Out << ")";
  1596. }
  1597. static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
  1598. TypePrinting *TypePrinter, SlotTracker *Machine,
  1599. const Module *Context) {
  1600. Out << "!DIObjCProperty(";
  1601. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1602. Printer.printString("name", N->getName());
  1603. Printer.printMetadata("file", N->getRawFile());
  1604. Printer.printInt("line", N->getLine());
  1605. Printer.printString("setter", N->getSetterName());
  1606. Printer.printString("getter", N->getGetterName());
  1607. Printer.printInt("attributes", N->getAttributes());
  1608. Printer.printMetadata("type", N->getRawType());
  1609. Out << ")";
  1610. }
  1611. static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
  1612. TypePrinting *TypePrinter,
  1613. SlotTracker *Machine, const Module *Context) {
  1614. Out << "!DIImportedEntity(";
  1615. MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
  1616. Printer.printTag(N);
  1617. Printer.printString("name", N->getName());
  1618. Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
  1619. Printer.printMetadata("entity", N->getRawEntity());
  1620. Printer.printInt("line", N->getLine());
  1621. Out << ")";
  1622. }
  1623. static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
  1624. TypePrinting *TypePrinter,
  1625. SlotTracker *Machine,
  1626. const Module *Context) {
  1627. if (Node->isDistinct())
  1628. Out << "distinct ";
  1629. else if (Node->isTemporary())
  1630. Out << "<temporary!> "; // Handle broken code.
  1631. switch (Node->getMetadataID()) {
  1632. default:
  1633. llvm_unreachable("Expected uniquable MDNode");
  1634. #define HANDLE_MDNODE_LEAF(CLASS) \
  1635. case Metadata::CLASS##Kind: \
  1636. write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
  1637. break;
  1638. #include "llvm/IR/Metadata.def"
  1639. }
  1640. }
  1641. // Full implementation of printing a Value as an operand with support for
  1642. // TypePrinting, etc.
  1643. static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
  1644. TypePrinting *TypePrinter,
  1645. SlotTracker *Machine,
  1646. const Module *Context) {
  1647. if (V->hasName()) {
  1648. PrintLLVMName(Out, V);
  1649. return;
  1650. }
  1651. const Constant *CV = dyn_cast<Constant>(V);
  1652. if (CV && !isa<GlobalValue>(CV)) {
  1653. assert(TypePrinter && "Constants require TypePrinting!");
  1654. WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
  1655. return;
  1656. }
  1657. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  1658. Out << "asm ";
  1659. if (IA->hasSideEffects())
  1660. Out << "sideeffect ";
  1661. if (IA->isAlignStack())
  1662. Out << "alignstack ";
  1663. // We don't emit the AD_ATT dialect as it's the assumed default.
  1664. if (IA->getDialect() == InlineAsm::AD_Intel)
  1665. Out << "inteldialect ";
  1666. Out << '"';
  1667. PrintEscapedString(IA->getAsmString(), Out);
  1668. Out << "\", \"";
  1669. PrintEscapedString(IA->getConstraintString(), Out);
  1670. Out << '"';
  1671. return;
  1672. }
  1673. if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
  1674. WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
  1675. Context, /* FromValue */ true);
  1676. return;
  1677. }
  1678. char Prefix = '%';
  1679. int Slot;
  1680. // If we have a SlotTracker, use it.
  1681. if (Machine) {
  1682. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  1683. Slot = Machine->getGlobalSlot(GV);
  1684. Prefix = '@';
  1685. } else {
  1686. Slot = Machine->getLocalSlot(V);
  1687. // If the local value didn't succeed, then we may be referring to a value
  1688. // from a different function. Translate it, as this can happen when using
  1689. // address of blocks.
  1690. if (Slot == -1)
  1691. if ((Machine = createSlotTracker(V))) {
  1692. Slot = Machine->getLocalSlot(V);
  1693. delete Machine;
  1694. }
  1695. }
  1696. } else if ((Machine = createSlotTracker(V))) {
  1697. // Otherwise, create one to get the # and then destroy it.
  1698. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  1699. Slot = Machine->getGlobalSlot(GV);
  1700. Prefix = '@';
  1701. } else {
  1702. Slot = Machine->getLocalSlot(V);
  1703. }
  1704. delete Machine;
  1705. Machine = nullptr;
  1706. } else {
  1707. Slot = -1;
  1708. }
  1709. if (Slot != -1)
  1710. Out << Prefix << Slot;
  1711. else
  1712. Out << "<badref>";
  1713. }
  1714. static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
  1715. TypePrinting *TypePrinter,
  1716. SlotTracker *Machine, const Module *Context,
  1717. bool FromValue) {
  1718. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1719. std::unique_ptr<SlotTracker> MachineStorage;
  1720. if (!Machine) {
  1721. MachineStorage = make_unique<SlotTracker>(Context);
  1722. Machine = MachineStorage.get();
  1723. }
  1724. int Slot = Machine->getMetadataSlot(N);
  1725. if (Slot == -1)
  1726. // Give the pointer value instead of "badref", since this comes up all
  1727. // the time when debugging.
  1728. Out << "<" << N << ">";
  1729. else
  1730. Out << '!' << Slot;
  1731. return;
  1732. }
  1733. if (const MDString *MDS = dyn_cast<MDString>(MD)) {
  1734. Out << "!\"";
  1735. PrintEscapedString(MDS->getString(), Out);
  1736. Out << '"';
  1737. return;
  1738. }
  1739. auto *V = cast<ValueAsMetadata>(MD);
  1740. assert(TypePrinter && "TypePrinter required for metadata values");
  1741. assert((FromValue || !isa<LocalAsMetadata>(V)) &&
  1742. "Unexpected function-local metadata outside of value argument");
  1743. TypePrinter->print(V->getValue()->getType(), Out);
  1744. Out << ' ';
  1745. WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
  1746. }
  1747. namespace {
  1748. class AssemblyWriter {
  1749. formatted_raw_ostream &Out;
  1750. const Module *TheModule;
  1751. std::unique_ptr<SlotTracker> SlotTrackerStorage;
  1752. SlotTracker &Machine;
  1753. TypePrinting TypePrinter;
  1754. AssemblyAnnotationWriter *AnnotationWriter;
  1755. SetVector<const Comdat *> Comdats;
  1756. bool ShouldPreserveUseListOrder;
  1757. UseListOrderStack UseListOrders;
  1758. SmallVector<StringRef, 8> MDNames;
  1759. public:
  1760. /// Construct an AssemblyWriter with an external SlotTracker
  1761. AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
  1762. AssemblyAnnotationWriter *AAW,
  1763. bool ShouldPreserveUseListOrder = false);
  1764. /// Construct an AssemblyWriter with an internally allocated SlotTracker
  1765. AssemblyWriter(formatted_raw_ostream &o, const Module *M,
  1766. AssemblyAnnotationWriter *AAW,
  1767. bool ShouldPreserveUseListOrder = false);
  1768. void printMDNodeBody(const MDNode *MD);
  1769. void printNamedMDNode(const NamedMDNode *NMD);
  1770. void printModule(const Module *M);
  1771. void writeOperand(const Value *Op, bool PrintType);
  1772. void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
  1773. void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
  1774. void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
  1775. AtomicOrdering FailureOrdering,
  1776. SynchronizationScope SynchScope);
  1777. void writeAllMDNodes();
  1778. void writeMDNode(unsigned Slot, const MDNode *Node);
  1779. void writeAllAttributeGroups();
  1780. void printTypeIdentities();
  1781. void printGlobal(const GlobalVariable *GV);
  1782. void printAlias(const GlobalAlias *GV);
  1783. void printComdat(const Comdat *C);
  1784. void printFunction(const Function *F);
  1785. void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
  1786. void printBasicBlock(const BasicBlock *BB);
  1787. void printInstructionLine(const Instruction &I);
  1788. void printInstruction(const Instruction &I);
  1789. void printUseListOrder(const UseListOrder &Order);
  1790. void printUseLists(const Function *F);
  1791. private:
  1792. void init();
  1793. /// \brief Print out metadata attachments.
  1794. void printMetadataAttachments(
  1795. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  1796. StringRef Separator);
  1797. // printInfoComment - Print a little comment after the instruction indicating
  1798. // which slot it occupies.
  1799. void printInfoComment(const Value &V);
  1800. // printGCRelocateComment - print comment after call to the gc.relocate
  1801. // intrinsic indicating base and derived pointer names.
  1802. void printGCRelocateComment(const Value &V);
  1803. };
  1804. } // namespace
  1805. void AssemblyWriter::init() {
  1806. if (!TheModule)
  1807. return;
  1808. TypePrinter.incorporateTypes(*TheModule);
  1809. for (const Function &F : *TheModule)
  1810. if (const Comdat *C = F.getComdat())
  1811. Comdats.insert(C);
  1812. for (const GlobalVariable &GV : TheModule->globals())
  1813. if (const Comdat *C = GV.getComdat())
  1814. Comdats.insert(C);
  1815. }
  1816. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
  1817. const Module *M, AssemblyAnnotationWriter *AAW,
  1818. bool ShouldPreserveUseListOrder)
  1819. : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
  1820. ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  1821. init();
  1822. }
  1823. #if 0 // HLSL Change - Unused
  1824. AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
  1825. AssemblyAnnotationWriter *AAW,
  1826. bool ShouldPreserveUseListOrder)
  1827. : Out(o), TheModule(M), SlotTrackerStorage(createSlotTracker(M)),
  1828. Machine(*SlotTrackerStorage), AnnotationWriter(AAW),
  1829. ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  1830. init();
  1831. }
  1832. #endif
  1833. void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
  1834. if (!Operand) {
  1835. Out << "<null operand!>";
  1836. return;
  1837. }
  1838. if (PrintType) {
  1839. TypePrinter.print(Operand->getType(), Out);
  1840. Out << ' ';
  1841. }
  1842. WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
  1843. }
  1844. void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
  1845. SynchronizationScope SynchScope) {
  1846. if (Ordering == NotAtomic)
  1847. return;
  1848. switch (SynchScope) {
  1849. case SingleThread: Out << " singlethread"; break;
  1850. case CrossThread: break;
  1851. }
  1852. switch (Ordering) {
  1853. default: Out << " <bad ordering " << int(Ordering) << ">"; break;
  1854. case Unordered: Out << " unordered"; break;
  1855. case Monotonic: Out << " monotonic"; break;
  1856. case Acquire: Out << " acquire"; break;
  1857. case Release: Out << " release"; break;
  1858. case AcquireRelease: Out << " acq_rel"; break;
  1859. case SequentiallyConsistent: Out << " seq_cst"; break;
  1860. }
  1861. }
  1862. void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
  1863. AtomicOrdering FailureOrdering,
  1864. SynchronizationScope SynchScope) {
  1865. assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
  1866. switch (SynchScope) {
  1867. case SingleThread: Out << " singlethread"; break;
  1868. case CrossThread: break;
  1869. }
  1870. switch (SuccessOrdering) {
  1871. default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
  1872. case Unordered: Out << " unordered"; break;
  1873. case Monotonic: Out << " monotonic"; break;
  1874. case Acquire: Out << " acquire"; break;
  1875. case Release: Out << " release"; break;
  1876. case AcquireRelease: Out << " acq_rel"; break;
  1877. case SequentiallyConsistent: Out << " seq_cst"; break;
  1878. }
  1879. switch (FailureOrdering) {
  1880. default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
  1881. case Unordered: Out << " unordered"; break;
  1882. case Monotonic: Out << " monotonic"; break;
  1883. case Acquire: Out << " acquire"; break;
  1884. case Release: Out << " release"; break;
  1885. case AcquireRelease: Out << " acq_rel"; break;
  1886. case SequentiallyConsistent: Out << " seq_cst"; break;
  1887. }
  1888. }
  1889. void AssemblyWriter::writeParamOperand(const Value *Operand,
  1890. AttributeSet Attrs, unsigned Idx) {
  1891. if (!Operand) {
  1892. Out << "<null operand!>";
  1893. return;
  1894. }
  1895. // Print the type
  1896. TypePrinter.print(Operand->getType(), Out);
  1897. // Print parameter attributes list
  1898. if (Attrs.hasAttributes(Idx))
  1899. Out << ' ' << Attrs.getAsString(Idx);
  1900. Out << ' ';
  1901. // Print the operand
  1902. WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
  1903. }
  1904. void AssemblyWriter::printModule(const Module *M) {
  1905. Machine.initialize();
  1906. if (ShouldPreserveUseListOrder)
  1907. UseListOrders = predictUseListOrder(M);
  1908. if (!M->getModuleIdentifier().empty() &&
  1909. // Don't print the ID if it will start a new line (which would
  1910. // require a comment char before it).
  1911. M->getModuleIdentifier().find('\n') == std::string::npos)
  1912. Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
  1913. const std::string &DL = M->getDataLayoutStr();
  1914. if (!DL.empty())
  1915. Out << "target datalayout = \"" << DL << "\"\n";
  1916. if (!M->getTargetTriple().empty())
  1917. Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
  1918. if (!M->getModuleInlineAsm().empty()) {
  1919. Out << '\n';
  1920. // Split the string into lines, to make it easier to read the .ll file.
  1921. StringRef Asm = M->getModuleInlineAsm();
  1922. do {
  1923. StringRef Front;
  1924. std::tie(Front, Asm) = Asm.split('\n');
  1925. // We found a newline, print the portion of the asm string from the
  1926. // last newline up to this newline.
  1927. Out << "module asm \"";
  1928. PrintEscapedString(Front, Out);
  1929. Out << "\"\n";
  1930. } while (!Asm.empty());
  1931. }
  1932. printTypeIdentities();
  1933. // Output all comdats.
  1934. if (!Comdats.empty())
  1935. Out << '\n';
  1936. for (const Comdat *C : Comdats) {
  1937. printComdat(C);
  1938. if (C != Comdats.back())
  1939. Out << '\n';
  1940. }
  1941. // Output all globals.
  1942. if (!M->global_empty()) Out << '\n';
  1943. for (const GlobalVariable &GV : M->globals()) {
  1944. printGlobal(&GV); Out << '\n';
  1945. }
  1946. // Output all aliases.
  1947. if (!M->alias_empty()) Out << "\n";
  1948. for (const GlobalAlias &GA : M->aliases())
  1949. printAlias(&GA);
  1950. // Output global use-lists.
  1951. printUseLists(nullptr);
  1952. // Output all of the functions.
  1953. for (const Function &F : *M)
  1954. printFunction(&F);
  1955. assert(UseListOrders.empty() && "All use-lists should have been consumed");
  1956. // Output all attribute groups.
  1957. if (!Machine.as_empty()) {
  1958. Out << '\n';
  1959. writeAllAttributeGroups();
  1960. }
  1961. // Output named metadata.
  1962. if (!M->named_metadata_empty()) Out << '\n';
  1963. for (const NamedMDNode &Node : M->named_metadata())
  1964. printNamedMDNode(&Node);
  1965. // Output metadata.
  1966. if (!Machine.mdn_empty()) {
  1967. Out << '\n';
  1968. writeAllMDNodes();
  1969. }
  1970. }
  1971. static void printMetadataIdentifier(StringRef Name,
  1972. formatted_raw_ostream &Out) {
  1973. if (Name.empty()) {
  1974. Out << "<empty name> ";
  1975. } else {
  1976. if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
  1977. Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
  1978. Out << Name[0];
  1979. else
  1980. Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
  1981. for (unsigned i = 1, e = Name.size(); i != e; ++i) {
  1982. unsigned char C = Name[i];
  1983. if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
  1984. C == '.' || C == '_')
  1985. Out << C;
  1986. else
  1987. Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  1988. }
  1989. }
  1990. }
  1991. void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
  1992. Out << '!';
  1993. printMetadataIdentifier(NMD->getName(), Out);
  1994. Out << " = !{";
  1995. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  1996. if (i)
  1997. Out << ", ";
  1998. int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
  1999. if (Slot == -1)
  2000. Out << "<badref>";
  2001. else
  2002. Out << '!' << Slot;
  2003. }
  2004. Out << "}\n";
  2005. }
  2006. static void PrintLinkage(GlobalValue::LinkageTypes LT,
  2007. formatted_raw_ostream &Out) {
  2008. switch (LT) {
  2009. case GlobalValue::ExternalLinkage: break;
  2010. case GlobalValue::PrivateLinkage: Out << "private "; break;
  2011. case GlobalValue::InternalLinkage: Out << "internal "; break;
  2012. case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
  2013. case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
  2014. case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
  2015. case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
  2016. case GlobalValue::CommonLinkage: Out << "common "; break;
  2017. case GlobalValue::AppendingLinkage: Out << "appending "; break;
  2018. case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
  2019. case GlobalValue::AvailableExternallyLinkage:
  2020. Out << "available_externally ";
  2021. break;
  2022. }
  2023. }
  2024. static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
  2025. formatted_raw_ostream &Out) {
  2026. switch (Vis) {
  2027. case GlobalValue::DefaultVisibility: break;
  2028. case GlobalValue::HiddenVisibility: Out << "hidden "; break;
  2029. case GlobalValue::ProtectedVisibility: Out << "protected "; break;
  2030. }
  2031. }
  2032. static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
  2033. formatted_raw_ostream &Out) {
  2034. switch (SCT) {
  2035. case GlobalValue::DefaultStorageClass: break;
  2036. case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
  2037. case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
  2038. }
  2039. }
  2040. static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
  2041. formatted_raw_ostream &Out) {
  2042. switch (TLM) {
  2043. case GlobalVariable::NotThreadLocal:
  2044. break;
  2045. case GlobalVariable::GeneralDynamicTLSModel:
  2046. Out << "thread_local ";
  2047. break;
  2048. case GlobalVariable::LocalDynamicTLSModel:
  2049. Out << "thread_local(localdynamic) ";
  2050. break;
  2051. case GlobalVariable::InitialExecTLSModel:
  2052. Out << "thread_local(initialexec) ";
  2053. break;
  2054. case GlobalVariable::LocalExecTLSModel:
  2055. Out << "thread_local(localexec) ";
  2056. break;
  2057. }
  2058. }
  2059. static void maybePrintComdat(formatted_raw_ostream &Out,
  2060. const GlobalObject &GO) {
  2061. const Comdat *C = GO.getComdat();
  2062. if (!C)
  2063. return;
  2064. if (isa<GlobalVariable>(GO))
  2065. Out << ',';
  2066. Out << " comdat";
  2067. if (GO.getName() == C->getName())
  2068. return;
  2069. Out << '(';
  2070. PrintLLVMName(Out, C->getName(), ComdatPrefix);
  2071. Out << ')';
  2072. }
  2073. void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
  2074. if (GV->isMaterializable())
  2075. Out << "; Materializable\n";
  2076. WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
  2077. Out << " = ";
  2078. if (!GV->hasInitializer() && GV->hasExternalLinkage())
  2079. Out << "external ";
  2080. PrintLinkage(GV->getLinkage(), Out);
  2081. PrintVisibility(GV->getVisibility(), Out);
  2082. PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
  2083. PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
  2084. if (GV->hasUnnamedAddr())
  2085. Out << "unnamed_addr ";
  2086. if (unsigned AddressSpace = GV->getType()->getAddressSpace())
  2087. Out << "addrspace(" << AddressSpace << ") ";
  2088. if (GV->isExternallyInitialized()) Out << "externally_initialized ";
  2089. Out << (GV->isConstant() ? "constant " : "global ");
  2090. TypePrinter.print(GV->getType()->getElementType(), Out);
  2091. if (GV->hasInitializer()) {
  2092. Out << ' ';
  2093. writeOperand(GV->getInitializer(), false);
  2094. }
  2095. if (GV->hasSection()) {
  2096. Out << ", section \"";
  2097. PrintEscapedString(GV->getSection(), Out);
  2098. Out << '"';
  2099. }
  2100. maybePrintComdat(Out, *GV);
  2101. if (GV->getAlignment())
  2102. Out << ", align " << GV->getAlignment();
  2103. printInfoComment(*GV);
  2104. }
  2105. void AssemblyWriter::printAlias(const GlobalAlias *GA) {
  2106. if (GA->isMaterializable())
  2107. Out << "; Materializable\n";
  2108. WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
  2109. Out << " = ";
  2110. PrintLinkage(GA->getLinkage(), Out);
  2111. PrintVisibility(GA->getVisibility(), Out);
  2112. PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
  2113. PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
  2114. if (GA->hasUnnamedAddr())
  2115. Out << "unnamed_addr ";
  2116. Out << "alias ";
  2117. const Constant *Aliasee = GA->getAliasee();
  2118. if (!Aliasee) {
  2119. TypePrinter.print(GA->getType(), Out);
  2120. Out << " <<NULL ALIASEE>>";
  2121. } else {
  2122. writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
  2123. }
  2124. printInfoComment(*GA);
  2125. Out << '\n';
  2126. }
  2127. void AssemblyWriter::printComdat(const Comdat *C) {
  2128. C->print(Out);
  2129. }
  2130. void AssemblyWriter::printTypeIdentities() {
  2131. if (TypePrinter.NumberedTypes.empty() &&
  2132. TypePrinter.NamedTypes.empty())
  2133. return;
  2134. Out << '\n';
  2135. // We know all the numbers that each type is used and we know that it is a
  2136. // dense assignment. Convert the map to an index table.
  2137. std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
  2138. for (DenseMap<StructType*, unsigned>::iterator I =
  2139. TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
  2140. I != E; ++I) {
  2141. assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
  2142. NumberedTypes[I->second] = I->first;
  2143. }
  2144. // Emit all numbered types.
  2145. for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
  2146. Out << '%' << i << " = type ";
  2147. // Make sure we print out at least one level of the type structure, so
  2148. // that we do not get %2 = type %2
  2149. TypePrinter.printStructBody(NumberedTypes[i], Out);
  2150. Out << '\n';
  2151. }
  2152. for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
  2153. PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
  2154. Out << " = type ";
  2155. // Make sure we print out at least one level of the type structure, so
  2156. // that we do not get %FILE = type %FILE
  2157. TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
  2158. Out << '\n';
  2159. }
  2160. }
  2161. /// printFunction - Print all aspects of a function.
  2162. ///
  2163. void AssemblyWriter::printFunction(const Function *F) {
  2164. // Print out the return type and name.
  2165. Out << '\n';
  2166. if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
  2167. if (F->isMaterializable())
  2168. Out << "; Materializable\n";
  2169. const AttributeSet &Attrs = F->getAttributes();
  2170. if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
  2171. AttributeSet AS = Attrs.getFnAttributes();
  2172. std::string AttrStr;
  2173. unsigned Idx = 0;
  2174. for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
  2175. if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
  2176. break;
  2177. for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
  2178. I != E; ++I) {
  2179. Attribute Attr = *I;
  2180. if (!Attr.isStringAttribute()) {
  2181. if (!AttrStr.empty()) AttrStr += ' ';
  2182. AttrStr += Attr.getAsString();
  2183. }
  2184. }
  2185. if (!AttrStr.empty())
  2186. Out << "; Function Attrs: " << AttrStr << '\n';
  2187. }
  2188. if (F->isDeclaration())
  2189. Out << "declare ";
  2190. else
  2191. Out << "define ";
  2192. PrintLinkage(F->getLinkage(), Out);
  2193. PrintVisibility(F->getVisibility(), Out);
  2194. PrintDLLStorageClass(F->getDLLStorageClass(), Out);
  2195. // Print the calling convention.
  2196. if (F->getCallingConv() != CallingConv::C) {
  2197. PrintCallingConv(F->getCallingConv(), Out);
  2198. Out << " ";
  2199. }
  2200. FunctionType *FT = F->getFunctionType();
  2201. if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
  2202. Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
  2203. TypePrinter.print(F->getReturnType(), Out);
  2204. Out << ' ';
  2205. WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
  2206. Out << '(';
  2207. Machine.incorporateFunction(F);
  2208. // Loop over the arguments, printing them...
  2209. unsigned Idx = 1;
  2210. if (!F->isDeclaration()) {
  2211. // If this isn't a declaration, print the argument names as well.
  2212. for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  2213. I != E; ++I) {
  2214. // Insert commas as we go... the first arg doesn't get a comma
  2215. if (I != F->arg_begin()) Out << ", ";
  2216. printArgument(I, Attrs, Idx);
  2217. Idx++;
  2218. }
  2219. } else {
  2220. // Otherwise, print the types from the function type.
  2221. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  2222. // Insert commas as we go... the first arg doesn't get a comma
  2223. if (i) Out << ", ";
  2224. // Output type...
  2225. TypePrinter.print(FT->getParamType(i), Out);
  2226. if (Attrs.hasAttributes(i+1))
  2227. Out << ' ' << Attrs.getAsString(i+1);
  2228. }
  2229. }
  2230. // Finish printing arguments...
  2231. if (FT->isVarArg()) {
  2232. if (FT->getNumParams()) Out << ", ";
  2233. Out << "..."; // Output varargs portion of signature!
  2234. }
  2235. Out << ')';
  2236. if (F->hasUnnamedAddr())
  2237. Out << " unnamed_addr";
  2238. if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
  2239. Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
  2240. if (F->hasSection()) {
  2241. Out << " section \"";
  2242. PrintEscapedString(F->getSection(), Out);
  2243. Out << '"';
  2244. }
  2245. maybePrintComdat(Out, *F);
  2246. if (F->getAlignment())
  2247. Out << " align " << F->getAlignment();
  2248. if (F->hasGC())
  2249. Out << " gc \"" << F->getGC() << '"';
  2250. if (F->hasPrefixData()) {
  2251. Out << " prefix ";
  2252. writeOperand(F->getPrefixData(), true);
  2253. }
  2254. if (F->hasPrologueData()) {
  2255. Out << " prologue ";
  2256. writeOperand(F->getPrologueData(), true);
  2257. }
  2258. if (F->hasPersonalityFn()) {
  2259. Out << " personality ";
  2260. writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
  2261. }
  2262. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  2263. F->getAllMetadata(MDs);
  2264. printMetadataAttachments(MDs, " ");
  2265. if (F->isDeclaration()) {
  2266. Out << '\n';
  2267. } else {
  2268. Out << " {";
  2269. // Output all of the function's basic blocks.
  2270. for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
  2271. printBasicBlock(I);
  2272. // Output the function's use-lists.
  2273. printUseLists(F);
  2274. Out << "}\n";
  2275. }
  2276. Machine.purgeFunction();
  2277. }
  2278. /// printArgument - This member is called for every argument that is passed into
  2279. /// the function. Simply print it out
  2280. ///
  2281. void AssemblyWriter::printArgument(const Argument *Arg,
  2282. AttributeSet Attrs, unsigned Idx) {
  2283. // Output type...
  2284. TypePrinter.print(Arg->getType(), Out);
  2285. // Output parameter attributes list
  2286. if (Attrs.hasAttributes(Idx))
  2287. Out << ' ' << Attrs.getAsString(Idx);
  2288. // Output name, if available...
  2289. if (Arg->hasName()) {
  2290. Out << ' ';
  2291. PrintLLVMName(Out, Arg);
  2292. }
  2293. }
  2294. /// printBasicBlock - This member is called for each basic block in a method.
  2295. ///
  2296. void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
  2297. if (BB->hasName()) { // Print out the label if it exists...
  2298. Out << "\n";
  2299. PrintLLVMName(Out, BB->getName(), LabelPrefix);
  2300. Out << ':';
  2301. } else if (!BB->use_empty()) { // Don't print block # of no uses...
  2302. Out << "\n; <label>:";
  2303. int Slot = Machine.getLocalSlot(BB);
  2304. if (Slot != -1)
  2305. Out << Slot;
  2306. else
  2307. Out << "<badref>";
  2308. }
  2309. if (!BB->getParent()) {
  2310. Out.PadToColumn(50);
  2311. Out << "; Error: Block without parent!";
  2312. } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
  2313. // Output predecessors for the block.
  2314. Out.PadToColumn(50);
  2315. Out << ";";
  2316. const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  2317. if (PI == PE) {
  2318. Out << " No predecessors!";
  2319. } else {
  2320. Out << " preds = ";
  2321. writeOperand(*PI, false);
  2322. for (++PI; PI != PE; ++PI) {
  2323. Out << ", ";
  2324. writeOperand(*PI, false);
  2325. }
  2326. }
  2327. }
  2328. Out << "\n";
  2329. if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
  2330. // Output all of the instructions in the basic block...
  2331. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2332. printInstructionLine(*I);
  2333. }
  2334. if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
  2335. }
  2336. /// printInstructionLine - Print an instruction and a newline character.
  2337. void AssemblyWriter::printInstructionLine(const Instruction &I) {
  2338. printInstruction(I);
  2339. Out << '\n';
  2340. }
  2341. /// printGCRelocateComment - print comment after call to the gc.relocate
  2342. /// intrinsic indicating base and derived pointer names.
  2343. void AssemblyWriter::printGCRelocateComment(const Value &V) {
  2344. assert(isGCRelocate(&V));
  2345. GCRelocateOperands GCOps(cast<Instruction>(&V));
  2346. Out << " ; (";
  2347. writeOperand(GCOps.getBasePtr(), false);
  2348. Out << ", ";
  2349. writeOperand(GCOps.getDerivedPtr(), false);
  2350. Out << ")";
  2351. }
  2352. /// printInfoComment - Print a little comment after the instruction indicating
  2353. /// which slot it occupies.
  2354. ///
  2355. void AssemblyWriter::printInfoComment(const Value &V) {
  2356. if (isGCRelocate(&V))
  2357. printGCRelocateComment(V);
  2358. if (AnnotationWriter)
  2359. AnnotationWriter->printInfoComment(V, Out);
  2360. }
  2361. // This member is called for each Instruction in a function..
  2362. void AssemblyWriter::printInstruction(const Instruction &I) {
  2363. if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
  2364. // Print out indentation for an instruction.
  2365. Out << " ";
  2366. // Print out name if it exists...
  2367. if (I.hasName()) {
  2368. PrintLLVMName(Out, &I);
  2369. Out << " = ";
  2370. } else if (!I.getType()->isVoidTy()) {
  2371. // Print out the def slot taken.
  2372. int SlotNum = Machine.getLocalSlot(&I);
  2373. if (SlotNum == -1)
  2374. Out << "<badref> = ";
  2375. else
  2376. Out << '%' << SlotNum << " = ";
  2377. }
  2378. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  2379. if (CI->isMustTailCall())
  2380. Out << "musttail ";
  2381. else if (CI->isTailCall())
  2382. Out << "tail ";
  2383. }
  2384. // Print out the opcode...
  2385. Out << I.getOpcodeName();
  2386. // If this is an atomic load or store, print out the atomic marker.
  2387. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
  2388. (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
  2389. Out << " atomic";
  2390. if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
  2391. Out << " weak";
  2392. // If this is a volatile operation, print out the volatile marker.
  2393. if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
  2394. (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
  2395. (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
  2396. (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
  2397. Out << " volatile";
  2398. // Print out optimization information.
  2399. WriteOptimizationInfo(Out, &I);
  2400. // Print out the compare instruction predicates
  2401. if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
  2402. Out << ' ' << getPredicateText(CI->getPredicate());
  2403. // Print out the atomicrmw operation
  2404. if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
  2405. writeAtomicRMWOperation(Out, RMWI->getOperation());
  2406. // Print out the type of the operands...
  2407. const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
  2408. // Special case conditional branches to swizzle the condition out to the front
  2409. if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
  2410. const BranchInst &BI(cast<BranchInst>(I));
  2411. Out << ' ';
  2412. writeOperand(BI.getCondition(), true);
  2413. Out << ", ";
  2414. writeOperand(BI.getSuccessor(0), true);
  2415. Out << ", ";
  2416. writeOperand(BI.getSuccessor(1), true);
  2417. } else if (isa<SwitchInst>(I)) {
  2418. const SwitchInst& SI(cast<SwitchInst>(I));
  2419. // Special case switch instruction to get formatting nice and correct.
  2420. Out << ' ';
  2421. writeOperand(SI.getCondition(), true);
  2422. Out << ", ";
  2423. writeOperand(SI.getDefaultDest(), true);
  2424. Out << " [";
  2425. for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
  2426. i != e; ++i) {
  2427. Out << "\n ";
  2428. writeOperand(i.getCaseValue(), true);
  2429. Out << ", ";
  2430. writeOperand(i.getCaseSuccessor(), true);
  2431. }
  2432. Out << "\n ]";
  2433. } else if (isa<IndirectBrInst>(I)) {
  2434. // Special case indirectbr instruction to get formatting nice and correct.
  2435. Out << ' ';
  2436. writeOperand(Operand, true);
  2437. Out << ", [";
  2438. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
  2439. if (i != 1)
  2440. Out << ", ";
  2441. writeOperand(I.getOperand(i), true);
  2442. }
  2443. Out << ']';
  2444. } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
  2445. Out << ' ';
  2446. TypePrinter.print(I.getType(), Out);
  2447. Out << ' ';
  2448. for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
  2449. if (op) Out << ", ";
  2450. Out << "[ ";
  2451. writeOperand(PN->getIncomingValue(op), false); Out << ", ";
  2452. writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
  2453. }
  2454. } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
  2455. Out << ' ';
  2456. writeOperand(I.getOperand(0), true);
  2457. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  2458. Out << ", " << *i;
  2459. } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
  2460. Out << ' ';
  2461. writeOperand(I.getOperand(0), true); Out << ", ";
  2462. writeOperand(I.getOperand(1), true);
  2463. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  2464. Out << ", " << *i;
  2465. } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
  2466. Out << ' ';
  2467. TypePrinter.print(I.getType(), Out);
  2468. if (LPI->isCleanup() || LPI->getNumClauses() != 0)
  2469. Out << '\n';
  2470. if (LPI->isCleanup())
  2471. Out << " cleanup";
  2472. for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
  2473. if (i != 0 || LPI->isCleanup()) Out << "\n";
  2474. if (LPI->isCatch(i))
  2475. Out << " catch ";
  2476. else
  2477. Out << " filter ";
  2478. writeOperand(LPI->getClause(i), true);
  2479. }
  2480. } else if (isa<ReturnInst>(I) && !Operand) {
  2481. Out << " void";
  2482. } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  2483. // Print the calling convention being used.
  2484. if (CI->getCallingConv() != CallingConv::C) {
  2485. Out << " ";
  2486. PrintCallingConv(CI->getCallingConv(), Out);
  2487. }
  2488. Operand = CI->getCalledValue();
  2489. FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
  2490. Type *RetTy = FTy->getReturnType();
  2491. const AttributeSet &PAL = CI->getAttributes();
  2492. if (PAL.hasAttributes(AttributeSet::ReturnIndex))
  2493. Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
  2494. // If possible, print out the short form of the call instruction. We can
  2495. // only do this if the first argument is a pointer to a nonvararg function,
  2496. // and if the return type is not a pointer to a function.
  2497. //
  2498. Out << ' ';
  2499. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  2500. Out << ' ';
  2501. writeOperand(Operand, false);
  2502. Out << '(';
  2503. for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
  2504. if (op > 0)
  2505. Out << ", ";
  2506. writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
  2507. }
  2508. // Emit an ellipsis if this is a musttail call in a vararg function. This
  2509. // is only to aid readability, musttail calls forward varargs by default.
  2510. if (CI->isMustTailCall() && CI->getParent() &&
  2511. CI->getParent()->getParent() &&
  2512. CI->getParent()->getParent()->isVarArg())
  2513. Out << ", ...";
  2514. Out << ')';
  2515. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  2516. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
  2517. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
  2518. Operand = II->getCalledValue();
  2519. FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
  2520. Type *RetTy = FTy->getReturnType();
  2521. const AttributeSet &PAL = II->getAttributes();
  2522. // Print the calling convention being used.
  2523. if (II->getCallingConv() != CallingConv::C) {
  2524. Out << " ";
  2525. PrintCallingConv(II->getCallingConv(), Out);
  2526. }
  2527. if (PAL.hasAttributes(AttributeSet::ReturnIndex))
  2528. Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
  2529. // If possible, print out the short form of the invoke instruction. We can
  2530. // only do this if the first argument is a pointer to a nonvararg function,
  2531. // and if the return type is not a pointer to a function.
  2532. //
  2533. Out << ' ';
  2534. TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
  2535. Out << ' ';
  2536. writeOperand(Operand, false);
  2537. Out << '(';
  2538. for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
  2539. if (op)
  2540. Out << ", ";
  2541. writeParamOperand(II->getArgOperand(op), PAL, op + 1);
  2542. }
  2543. Out << ')';
  2544. if (PAL.hasAttributes(AttributeSet::FunctionIndex))
  2545. Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
  2546. Out << "\n to ";
  2547. writeOperand(II->getNormalDest(), true);
  2548. Out << " unwind ";
  2549. writeOperand(II->getUnwindDest(), true);
  2550. } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  2551. Out << ' ';
  2552. if (AI->isUsedWithInAlloca())
  2553. Out << "inalloca ";
  2554. TypePrinter.print(AI->getAllocatedType(), Out);
  2555. // Explicitly write the array size if the code is broken, if it's an array
  2556. // allocation, or if the type is not canonical for scalar allocations. The
  2557. // latter case prevents the type from mutating when round-tripping through
  2558. // assembly.
  2559. if (!AI->getArraySize() || AI->isArrayAllocation() ||
  2560. !AI->getArraySize()->getType()->isIntegerTy(32)) {
  2561. Out << ", ";
  2562. writeOperand(AI->getArraySize(), true);
  2563. }
  2564. if (AI->getAlignment()) {
  2565. Out << ", align " << AI->getAlignment();
  2566. }
  2567. } else if (isa<CastInst>(I)) {
  2568. if (Operand) {
  2569. Out << ' ';
  2570. writeOperand(Operand, true); // Work with broken code
  2571. }
  2572. Out << " to ";
  2573. TypePrinter.print(I.getType(), Out);
  2574. } else if (isa<VAArgInst>(I)) {
  2575. if (Operand) {
  2576. Out << ' ';
  2577. writeOperand(Operand, true); // Work with broken code
  2578. }
  2579. Out << ", ";
  2580. TypePrinter.print(I.getType(), Out);
  2581. } else if (Operand) { // Print the normal way.
  2582. if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  2583. Out << ' ';
  2584. TypePrinter.print(GEP->getSourceElementType(), Out);
  2585. Out << ',';
  2586. } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
  2587. Out << ' ';
  2588. TypePrinter.print(LI->getType(), Out);
  2589. Out << ',';
  2590. }
  2591. // PrintAllTypes - Instructions who have operands of all the same type
  2592. // omit the type from all but the first operand. If the instruction has
  2593. // different type operands (for example br), then they are all printed.
  2594. bool PrintAllTypes = false;
  2595. Type *TheType = Operand->getType();
  2596. // Select, Store and ShuffleVector always print all types.
  2597. if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
  2598. || isa<ReturnInst>(I)) {
  2599. PrintAllTypes = true;
  2600. } else {
  2601. for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
  2602. Operand = I.getOperand(i);
  2603. // note that Operand shouldn't be null, but the test helps make dump()
  2604. // more tolerant of malformed IR
  2605. if (Operand && Operand->getType() != TheType) {
  2606. PrintAllTypes = true; // We have differing types! Print them all!
  2607. break;
  2608. }
  2609. }
  2610. }
  2611. if (!PrintAllTypes) {
  2612. Out << ' ';
  2613. TypePrinter.print(TheType, Out);
  2614. }
  2615. Out << ' ';
  2616. for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
  2617. if (i) Out << ", ";
  2618. writeOperand(I.getOperand(i), PrintAllTypes);
  2619. }
  2620. }
  2621. // Print atomic ordering/alignment for memory operations
  2622. if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
  2623. if (LI->isAtomic())
  2624. writeAtomic(LI->getOrdering(), LI->getSynchScope());
  2625. if (LI->getAlignment())
  2626. Out << ", align " << LI->getAlignment();
  2627. } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  2628. if (SI->isAtomic())
  2629. writeAtomic(SI->getOrdering(), SI->getSynchScope());
  2630. if (SI->getAlignment())
  2631. Out << ", align " << SI->getAlignment();
  2632. } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
  2633. writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
  2634. CXI->getSynchScope());
  2635. } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
  2636. writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
  2637. } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
  2638. writeAtomic(FI->getOrdering(), FI->getSynchScope());
  2639. }
  2640. // Print Metadata info.
  2641. SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
  2642. I.getAllMetadata(InstMD);
  2643. printMetadataAttachments(InstMD, ", ");
  2644. // Print a nice comment.
  2645. printInfoComment(I);
  2646. }
  2647. void AssemblyWriter::printMetadataAttachments(
  2648. const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
  2649. StringRef Separator) {
  2650. if (MDs.empty())
  2651. return;
  2652. if (MDNames.empty())
  2653. TheModule->getMDKindNames(MDNames);
  2654. for (const auto &I : MDs) {
  2655. unsigned Kind = I.first;
  2656. Out << Separator;
  2657. if (Kind < MDNames.size()) {
  2658. Out << "!";
  2659. printMetadataIdentifier(MDNames[Kind], Out);
  2660. } else
  2661. Out << "!<unknown kind #" << Kind << ">";
  2662. Out << ' ';
  2663. WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
  2664. }
  2665. }
  2666. void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
  2667. Out << '!' << Slot << " = ";
  2668. printMDNodeBody(Node);
  2669. Out << "\n";
  2670. }
  2671. void AssemblyWriter::writeAllMDNodes() {
  2672. SmallVector<const MDNode *, 16> Nodes;
  2673. Nodes.resize(Machine.mdn_size());
  2674. for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
  2675. I != E; ++I)
  2676. Nodes[I->second] = cast<MDNode>(I->first);
  2677. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  2678. writeMDNode(i, Nodes[i]);
  2679. }
  2680. }
  2681. void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
  2682. WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
  2683. }
  2684. void AssemblyWriter::writeAllAttributeGroups() {
  2685. std::vector<std::pair<AttributeSet, unsigned> > asVec;
  2686. asVec.resize(Machine.as_size());
  2687. for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
  2688. I != E; ++I)
  2689. asVec[I->second] = *I;
  2690. for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
  2691. I = asVec.begin(), E = asVec.end(); I != E; ++I)
  2692. Out << "attributes #" << I->second << " = { "
  2693. << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
  2694. }
  2695. void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
  2696. bool IsInFunction = Machine.getFunction();
  2697. if (IsInFunction)
  2698. Out << " ";
  2699. Out << "uselistorder";
  2700. if (const BasicBlock *BB =
  2701. IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
  2702. Out << "_bb ";
  2703. writeOperand(BB->getParent(), false);
  2704. Out << ", ";
  2705. writeOperand(BB, false);
  2706. } else {
  2707. Out << " ";
  2708. writeOperand(Order.V, true);
  2709. }
  2710. Out << ", { ";
  2711. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2712. Out << Order.Shuffle[0];
  2713. for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
  2714. Out << ", " << Order.Shuffle[I];
  2715. Out << " }\n";
  2716. }
  2717. void AssemblyWriter::printUseLists(const Function *F) {
  2718. auto hasMore =
  2719. [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
  2720. if (!hasMore())
  2721. // Nothing to do.
  2722. return;
  2723. Out << "\n; uselistorder directives\n";
  2724. while (hasMore()) {
  2725. printUseListOrder(UseListOrders.back());
  2726. UseListOrders.pop_back();
  2727. }
  2728. }
  2729. //===----------------------------------------------------------------------===//
  2730. // External Interface declarations
  2731. //===----------------------------------------------------------------------===//
  2732. void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
  2733. SlotTracker SlotTable(this->getParent());
  2734. formatted_raw_ostream OS(ROS);
  2735. AssemblyWriter W(OS, SlotTable, this->getParent(), AAW);
  2736. W.printFunction(this);
  2737. }
  2738. void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
  2739. bool ShouldPreserveUseListOrder) const {
  2740. SlotTracker SlotTable(this);
  2741. formatted_raw_ostream OS(ROS);
  2742. AssemblyWriter W(OS, SlotTable, this, AAW, ShouldPreserveUseListOrder);
  2743. W.printModule(this);
  2744. }
  2745. void NamedMDNode::print(raw_ostream &ROS) const {
  2746. SlotTracker SlotTable(getParent());
  2747. formatted_raw_ostream OS(ROS);
  2748. AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
  2749. W.printNamedMDNode(this);
  2750. }
  2751. void Comdat::print(raw_ostream &ROS) const {
  2752. PrintLLVMName(ROS, getName(), ComdatPrefix);
  2753. ROS << " = comdat ";
  2754. switch (getSelectionKind()) {
  2755. case Comdat::Any:
  2756. ROS << "any";
  2757. break;
  2758. case Comdat::ExactMatch:
  2759. ROS << "exactmatch";
  2760. break;
  2761. case Comdat::Largest:
  2762. ROS << "largest";
  2763. break;
  2764. case Comdat::NoDuplicates:
  2765. ROS << "noduplicates";
  2766. break;
  2767. case Comdat::SameSize:
  2768. ROS << "samesize";
  2769. break;
  2770. }
  2771. ROS << '\n';
  2772. }
  2773. void Type::print(raw_ostream &OS) const {
  2774. TypePrinting TP;
  2775. TP.print(const_cast<Type*>(this), OS);
  2776. // If the type is a named struct type, print the body as well.
  2777. if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
  2778. if (!STy->isLiteral()) {
  2779. OS << " = type ";
  2780. TP.printStructBody(STy, OS);
  2781. }
  2782. }
  2783. static bool isReferencingMDNode(const Instruction &I) {
  2784. if (const auto *CI = dyn_cast<CallInst>(&I))
  2785. if (Function *F = CI->getCalledFunction())
  2786. if (F->isIntrinsic())
  2787. for (auto &Op : I.operands())
  2788. if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
  2789. if (isa<MDNode>(V->getMetadata()))
  2790. return true;
  2791. return false;
  2792. }
  2793. void Value::print(raw_ostream &ROS) const {
  2794. bool ShouldInitializeAllMetadata = false;
  2795. if (auto *I = dyn_cast<Instruction>(this))
  2796. ShouldInitializeAllMetadata = isReferencingMDNode(*I);
  2797. else if (isa<Function>(this) || isa<MetadataAsValue>(this))
  2798. ShouldInitializeAllMetadata = true;
  2799. ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
  2800. print(ROS, MST);
  2801. }
  2802. void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST) const {
  2803. formatted_raw_ostream OS(ROS);
  2804. SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
  2805. SlotTracker &SlotTable =
  2806. MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
  2807. auto incorporateFunction = [&](const Function *F) {
  2808. if (F)
  2809. MST.incorporateFunction(*F);
  2810. };
  2811. if (const Instruction *I = dyn_cast<Instruction>(this)) {
  2812. incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
  2813. AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
  2814. W.printInstruction(*I);
  2815. } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
  2816. incorporateFunction(BB->getParent());
  2817. AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
  2818. W.printBasicBlock(BB);
  2819. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
  2820. AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
  2821. if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
  2822. W.printGlobal(V);
  2823. else if (const Function *F = dyn_cast<Function>(GV))
  2824. W.printFunction(F);
  2825. else
  2826. W.printAlias(cast<GlobalAlias>(GV));
  2827. } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
  2828. V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
  2829. } else if (const Constant *C = dyn_cast<Constant>(this)) {
  2830. TypePrinting TypePrinter;
  2831. TypePrinter.print(C->getType(), OS);
  2832. OS << ' ';
  2833. WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
  2834. } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
  2835. this->printAsOperand(OS, /* PrintType */ true, MST);
  2836. } else {
  2837. llvm_unreachable("Unknown value to print out!");
  2838. }
  2839. }
  2840. /// Print without a type, skipping the TypePrinting object.
  2841. ///
  2842. /// \return \c true iff printing was succesful.
  2843. static bool printWithoutType(const Value &V, raw_ostream &O,
  2844. SlotTracker *Machine, const Module *M) {
  2845. if (V.hasName() || isa<GlobalValue>(V) ||
  2846. (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
  2847. WriteAsOperandInternal(O, &V, nullptr, Machine, M);
  2848. return true;
  2849. }
  2850. return false;
  2851. }
  2852. static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
  2853. ModuleSlotTracker &MST) {
  2854. TypePrinting TypePrinter;
  2855. if (const Module *M = MST.getModule())
  2856. TypePrinter.incorporateTypes(*M);
  2857. if (PrintType) {
  2858. TypePrinter.print(V.getType(), O);
  2859. O << ' ';
  2860. }
  2861. WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
  2862. MST.getModule());
  2863. }
  2864. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  2865. const Module *M) const {
  2866. if (!M)
  2867. M = getModuleFromVal(this);
  2868. if (!PrintType)
  2869. if (printWithoutType(*this, O, nullptr, M))
  2870. return;
  2871. SlotTracker Machine(
  2872. M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
  2873. ModuleSlotTracker MST(Machine, M);
  2874. printAsOperandImpl(*this, O, PrintType, MST);
  2875. }
  2876. void Value::printAsOperand(raw_ostream &O, bool PrintType,
  2877. ModuleSlotTracker &MST) const {
  2878. if (!PrintType)
  2879. if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
  2880. return;
  2881. printAsOperandImpl(*this, O, PrintType, MST);
  2882. }
  2883. static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
  2884. ModuleSlotTracker &MST, const Module *M,
  2885. bool OnlyAsOperand) {
  2886. formatted_raw_ostream OS(ROS);
  2887. TypePrinting TypePrinter;
  2888. if (M)
  2889. TypePrinter.incorporateTypes(*M);
  2890. WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
  2891. /* FromValue */ true);
  2892. auto *N = dyn_cast<MDNode>(&MD);
  2893. if (OnlyAsOperand || !N)
  2894. return;
  2895. OS << " = ";
  2896. WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
  2897. }
  2898. void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
  2899. ModuleSlotTracker MST(M, isa<MDNode>(this));
  2900. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  2901. }
  2902. void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
  2903. const Module *M) const {
  2904. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
  2905. }
  2906. void Metadata::print(raw_ostream &OS, const Module *M) const {
  2907. ModuleSlotTracker MST(M, isa<MDNode>(this));
  2908. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  2909. }
  2910. void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
  2911. const Module *M) const {
  2912. printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
  2913. }
  2914. // HLSL Change Begin
  2915. void MDNode::printAsBody(raw_ostream &OS, const Module *M) const {
  2916. ModuleSlotTracker MST(M, true);
  2917. printAsBody(OS, MST, M);
  2918. }
  2919. void MDNode::printAsBody(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M) const {
  2920. TypePrinting TypePrinter;
  2921. if (M)
  2922. TypePrinter.incorporateTypes(*M);
  2923. WriteMDNodeBodyInternal(OS, this, &TypePrinter, MST.getMachine(), M);
  2924. }
  2925. // HLSL Change end
  2926. // Value::dump - allow easy printing of Values from the debugger.
  2927. LLVM_DUMP_METHOD
  2928. void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
  2929. // Type::dump - allow easy printing of Types from the debugger.
  2930. LLVM_DUMP_METHOD
  2931. void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
  2932. // Module::dump() - Allow printing of Modules from the debugger.
  2933. LLVM_DUMP_METHOD
  2934. void Module::dump() const { print(dbgs(), nullptr); }
  2935. // \brief Allow printing of Comdats from the debugger.
  2936. LLVM_DUMP_METHOD
  2937. void Comdat::dump() const { print(dbgs()); }
  2938. // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
  2939. LLVM_DUMP_METHOD
  2940. void NamedMDNode::dump() const { print(dbgs()); }
  2941. LLVM_DUMP_METHOD
  2942. void Metadata::dump() const { dump(nullptr); }
  2943. LLVM_DUMP_METHOD
  2944. void Metadata::dump(const Module *M) const {
  2945. print(dbgs(), M);
  2946. dbgs() << '\n';
  2947. }