X86MCInstLower.cpp 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  1. //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains code to lower X86 MachineInstrs to their corresponding
  10. // MCInst records.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "MCTargetDesc/X86ATTInstPrinter.h"
  14. #include "MCTargetDesc/X86BaseInfo.h"
  15. #include "MCTargetDesc/X86InstComments.h"
  16. #include "MCTargetDesc/X86ShuffleDecode.h"
  17. #include "MCTargetDesc/X86TargetStreamer.h"
  18. #include "X86AsmPrinter.h"
  19. #include "X86RegisterInfo.h"
  20. #include "X86ShuffleDecodeConstantPool.h"
  21. #include "X86Subtarget.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/iterator_range.h"
  24. #include "llvm/CodeGen/MachineConstantPool.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  27. #include "llvm/CodeGen/MachineOperand.h"
  28. #include "llvm/CodeGen/StackMaps.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/GlobalValue.h"
  31. #include "llvm/IR/Mangler.h"
  32. #include "llvm/MC/MCAsmInfo.h"
  33. #include "llvm/MC/MCCodeEmitter.h"
  34. #include "llvm/MC/MCContext.h"
  35. #include "llvm/MC/MCExpr.h"
  36. #include "llvm/MC/MCFixup.h"
  37. #include "llvm/MC/MCInst.h"
  38. #include "llvm/MC/MCInstBuilder.h"
  39. #include "llvm/MC/MCSection.h"
  40. #include "llvm/MC/MCSectionELF.h"
  41. #include "llvm/MC/MCStreamer.h"
  42. #include "llvm/MC/MCSymbol.h"
  43. #include "llvm/MC/MCSymbolELF.h"
  44. #include "llvm/MC/TargetRegistry.h"
  45. #include "llvm/Target/TargetLoweringObjectFile.h"
  46. #include "llvm/Target/TargetMachine.h"
  47. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  48. #include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
  49. #include <string>
  50. using namespace llvm;
  51. namespace {
  52. /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
  53. class X86MCInstLower {
  54. MCContext &Ctx;
  55. const MachineFunction &MF;
  56. const TargetMachine &TM;
  57. const MCAsmInfo &MAI;
  58. X86AsmPrinter &AsmPrinter;
  59. public:
  60. X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
  61. std::optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
  62. const MachineOperand &MO) const;
  63. void Lower(const MachineInstr *MI, MCInst &OutMI) const;
  64. MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
  65. MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
  66. private:
  67. MachineModuleInfoMachO &getMachOMMI() const;
  68. };
  69. } // end anonymous namespace
  70. /// A RAII helper which defines a region of instructions which can't have
  71. /// padding added between them for correctness.
  72. struct NoAutoPaddingScope {
  73. MCStreamer &OS;
  74. const bool OldAllowAutoPadding;
  75. NoAutoPaddingScope(MCStreamer &OS)
  76. : OS(OS), OldAllowAutoPadding(OS.getAllowAutoPadding()) {
  77. changeAndComment(false);
  78. }
  79. ~NoAutoPaddingScope() { changeAndComment(OldAllowAutoPadding); }
  80. void changeAndComment(bool b) {
  81. if (b == OS.getAllowAutoPadding())
  82. return;
  83. OS.setAllowAutoPadding(b);
  84. if (b)
  85. OS.emitRawComment("autopadding");
  86. else
  87. OS.emitRawComment("noautopadding");
  88. }
  89. };
  90. // Emit a minimal sequence of nops spanning NumBytes bytes.
  91. static void emitX86Nops(MCStreamer &OS, unsigned NumBytes,
  92. const X86Subtarget *Subtarget);
  93. void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
  94. const MCSubtargetInfo &STI,
  95. MCCodeEmitter *CodeEmitter) {
  96. if (InShadow) {
  97. SmallString<256> Code;
  98. SmallVector<MCFixup, 4> Fixups;
  99. raw_svector_ostream VecOS(Code);
  100. CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
  101. CurrentShadowSize += Code.size();
  102. if (CurrentShadowSize >= RequiredShadowSize)
  103. InShadow = false; // The shadow is big enough. Stop counting.
  104. }
  105. }
  106. void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
  107. MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
  108. if (InShadow && CurrentShadowSize < RequiredShadowSize) {
  109. InShadow = false;
  110. emitX86Nops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
  111. &MF->getSubtarget<X86Subtarget>());
  112. }
  113. }
  114. void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
  115. OutStreamer->emitInstruction(Inst, getSubtargetInfo());
  116. SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
  117. }
  118. X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
  119. X86AsmPrinter &asmprinter)
  120. : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
  121. AsmPrinter(asmprinter) {}
  122. MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
  123. return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
  124. }
  125. /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
  126. /// operand to an MCSymbol.
  127. MCSymbol *X86MCInstLower::GetSymbolFromOperand(const MachineOperand &MO) const {
  128. const Triple &TT = TM.getTargetTriple();
  129. if (MO.isGlobal() && TT.isOSBinFormatELF())
  130. return AsmPrinter.getSymbolPreferLocal(*MO.getGlobal());
  131. const DataLayout &DL = MF.getDataLayout();
  132. assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
  133. "Isn't a symbol reference");
  134. MCSymbol *Sym = nullptr;
  135. SmallString<128> Name;
  136. StringRef Suffix;
  137. switch (MO.getTargetFlags()) {
  138. case X86II::MO_DLLIMPORT:
  139. // Handle dllimport linkage.
  140. Name += "__imp_";
  141. break;
  142. case X86II::MO_COFFSTUB:
  143. Name += ".refptr.";
  144. break;
  145. case X86II::MO_DARWIN_NONLAZY:
  146. case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
  147. Suffix = "$non_lazy_ptr";
  148. break;
  149. }
  150. if (!Suffix.empty())
  151. Name += DL.getPrivateGlobalPrefix();
  152. if (MO.isGlobal()) {
  153. const GlobalValue *GV = MO.getGlobal();
  154. AsmPrinter.getNameWithPrefix(Name, GV);
  155. } else if (MO.isSymbol()) {
  156. Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
  157. } else if (MO.isMBB()) {
  158. assert(Suffix.empty());
  159. Sym = MO.getMBB()->getSymbol();
  160. }
  161. Name += Suffix;
  162. if (!Sym)
  163. Sym = Ctx.getOrCreateSymbol(Name);
  164. // If the target flags on the operand changes the name of the symbol, do that
  165. // before we return the symbol.
  166. switch (MO.getTargetFlags()) {
  167. default:
  168. break;
  169. case X86II::MO_COFFSTUB: {
  170. MachineModuleInfoCOFF &MMICOFF =
  171. MF.getMMI().getObjFileInfo<MachineModuleInfoCOFF>();
  172. MachineModuleInfoImpl::StubValueTy &StubSym = MMICOFF.getGVStubEntry(Sym);
  173. if (!StubSym.getPointer()) {
  174. assert(MO.isGlobal() && "Extern symbol not handled yet");
  175. StubSym = MachineModuleInfoImpl::StubValueTy(
  176. AsmPrinter.getSymbol(MO.getGlobal()), true);
  177. }
  178. break;
  179. }
  180. case X86II::MO_DARWIN_NONLAZY:
  181. case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
  182. MachineModuleInfoImpl::StubValueTy &StubSym =
  183. getMachOMMI().getGVStubEntry(Sym);
  184. if (!StubSym.getPointer()) {
  185. assert(MO.isGlobal() && "Extern symbol not handled yet");
  186. StubSym = MachineModuleInfoImpl::StubValueTy(
  187. AsmPrinter.getSymbol(MO.getGlobal()),
  188. !MO.getGlobal()->hasInternalLinkage());
  189. }
  190. break;
  191. }
  192. }
  193. return Sym;
  194. }
  195. MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
  196. MCSymbol *Sym) const {
  197. // FIXME: We would like an efficient form for this, so we don't have to do a
  198. // lot of extra uniquing.
  199. const MCExpr *Expr = nullptr;
  200. MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
  201. switch (MO.getTargetFlags()) {
  202. default:
  203. llvm_unreachable("Unknown target flag on GV operand");
  204. case X86II::MO_NO_FLAG: // No flag.
  205. // These affect the name of the symbol, not any suffix.
  206. case X86II::MO_DARWIN_NONLAZY:
  207. case X86II::MO_DLLIMPORT:
  208. case X86II::MO_COFFSTUB:
  209. break;
  210. case X86II::MO_TLVP:
  211. RefKind = MCSymbolRefExpr::VK_TLVP;
  212. break;
  213. case X86II::MO_TLVP_PIC_BASE:
  214. Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
  215. // Subtract the pic base.
  216. Expr = MCBinaryExpr::createSub(
  217. Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
  218. break;
  219. case X86II::MO_SECREL:
  220. RefKind = MCSymbolRefExpr::VK_SECREL;
  221. break;
  222. case X86II::MO_TLSGD:
  223. RefKind = MCSymbolRefExpr::VK_TLSGD;
  224. break;
  225. case X86II::MO_TLSLD:
  226. RefKind = MCSymbolRefExpr::VK_TLSLD;
  227. break;
  228. case X86II::MO_TLSLDM:
  229. RefKind = MCSymbolRefExpr::VK_TLSLDM;
  230. break;
  231. case X86II::MO_GOTTPOFF:
  232. RefKind = MCSymbolRefExpr::VK_GOTTPOFF;
  233. break;
  234. case X86II::MO_INDNTPOFF:
  235. RefKind = MCSymbolRefExpr::VK_INDNTPOFF;
  236. break;
  237. case X86II::MO_TPOFF:
  238. RefKind = MCSymbolRefExpr::VK_TPOFF;
  239. break;
  240. case X86II::MO_DTPOFF:
  241. RefKind = MCSymbolRefExpr::VK_DTPOFF;
  242. break;
  243. case X86II::MO_NTPOFF:
  244. RefKind = MCSymbolRefExpr::VK_NTPOFF;
  245. break;
  246. case X86II::MO_GOTNTPOFF:
  247. RefKind = MCSymbolRefExpr::VK_GOTNTPOFF;
  248. break;
  249. case X86II::MO_GOTPCREL:
  250. RefKind = MCSymbolRefExpr::VK_GOTPCREL;
  251. break;
  252. case X86II::MO_GOTPCREL_NORELAX:
  253. RefKind = MCSymbolRefExpr::VK_GOTPCREL_NORELAX;
  254. break;
  255. case X86II::MO_GOT:
  256. RefKind = MCSymbolRefExpr::VK_GOT;
  257. break;
  258. case X86II::MO_GOTOFF:
  259. RefKind = MCSymbolRefExpr::VK_GOTOFF;
  260. break;
  261. case X86II::MO_PLT:
  262. RefKind = MCSymbolRefExpr::VK_PLT;
  263. break;
  264. case X86II::MO_ABS8:
  265. RefKind = MCSymbolRefExpr::VK_X86_ABS8;
  266. break;
  267. case X86II::MO_PIC_BASE_OFFSET:
  268. case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
  269. Expr = MCSymbolRefExpr::create(Sym, Ctx);
  270. // Subtract the pic base.
  271. Expr = MCBinaryExpr::createSub(
  272. Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
  273. if (MO.isJTI()) {
  274. assert(MAI.doesSetDirectiveSuppressReloc());
  275. // If .set directive is supported, use it to reduce the number of
  276. // relocations the assembler will generate for differences between
  277. // local labels. This is only safe when the symbols are in the same
  278. // section so we are restricting it to jumptable references.
  279. MCSymbol *Label = Ctx.createTempSymbol();
  280. AsmPrinter.OutStreamer->emitAssignment(Label, Expr);
  281. Expr = MCSymbolRefExpr::create(Label, Ctx);
  282. }
  283. break;
  284. }
  285. if (!Expr)
  286. Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
  287. if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
  288. Expr = MCBinaryExpr::createAdd(
  289. Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
  290. return MCOperand::createExpr(Expr);
  291. }
  292. /// Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
  293. /// a short fixed-register form.
  294. static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
  295. unsigned ImmOp = Inst.getNumOperands() - 1;
  296. assert(Inst.getOperand(0).isReg() &&
  297. (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
  298. ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
  299. Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
  300. Inst.getNumOperands() == 2) &&
  301. "Unexpected instruction!");
  302. // Check whether the destination register can be fixed.
  303. unsigned Reg = Inst.getOperand(0).getReg();
  304. if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
  305. return;
  306. // If so, rewrite the instruction.
  307. MCOperand Saved = Inst.getOperand(ImmOp);
  308. Inst = MCInst();
  309. Inst.setOpcode(Opcode);
  310. Inst.addOperand(Saved);
  311. }
  312. /// If a movsx instruction has a shorter encoding for the used register
  313. /// simplify the instruction to use it instead.
  314. static void SimplifyMOVSX(MCInst &Inst) {
  315. unsigned NewOpcode = 0;
  316. unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
  317. switch (Inst.getOpcode()) {
  318. default:
  319. llvm_unreachable("Unexpected instruction!");
  320. case X86::MOVSX16rr8: // movsbw %al, %ax --> cbtw
  321. if (Op0 == X86::AX && Op1 == X86::AL)
  322. NewOpcode = X86::CBW;
  323. break;
  324. case X86::MOVSX32rr16: // movswl %ax, %eax --> cwtl
  325. if (Op0 == X86::EAX && Op1 == X86::AX)
  326. NewOpcode = X86::CWDE;
  327. break;
  328. case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
  329. if (Op0 == X86::RAX && Op1 == X86::EAX)
  330. NewOpcode = X86::CDQE;
  331. break;
  332. }
  333. if (NewOpcode != 0) {
  334. Inst = MCInst();
  335. Inst.setOpcode(NewOpcode);
  336. }
  337. }
  338. /// Simplify things like MOV32rm to MOV32o32a.
  339. static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
  340. unsigned Opcode) {
  341. // Don't make these simplifications in 64-bit mode; other assemblers don't
  342. // perform them because they make the code larger.
  343. if (Printer.getSubtarget().is64Bit())
  344. return;
  345. bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
  346. unsigned AddrBase = IsStore;
  347. unsigned RegOp = IsStore ? 0 : 5;
  348. unsigned AddrOp = AddrBase + 3;
  349. assert(
  350. Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
  351. Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
  352. Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
  353. Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
  354. Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
  355. (Inst.getOperand(AddrOp).isExpr() || Inst.getOperand(AddrOp).isImm()) &&
  356. "Unexpected instruction!");
  357. // Check whether the destination register can be fixed.
  358. unsigned Reg = Inst.getOperand(RegOp).getReg();
  359. if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
  360. return;
  361. // Check whether this is an absolute address.
  362. // FIXME: We know TLVP symbol refs aren't, but there should be a better way
  363. // to do this here.
  364. bool Absolute = true;
  365. if (Inst.getOperand(AddrOp).isExpr()) {
  366. const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
  367. if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
  368. if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
  369. Absolute = false;
  370. }
  371. if (Absolute &&
  372. (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
  373. Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
  374. Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
  375. return;
  376. // If so, rewrite the instruction.
  377. MCOperand Saved = Inst.getOperand(AddrOp);
  378. MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
  379. Inst = MCInst();
  380. Inst.setOpcode(Opcode);
  381. Inst.addOperand(Saved);
  382. Inst.addOperand(Seg);
  383. }
  384. static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
  385. return Subtarget.is64Bit() ? X86::RET64 : X86::RET32;
  386. }
  387. std::optional<MCOperand>
  388. X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
  389. const MachineOperand &MO) const {
  390. switch (MO.getType()) {
  391. default:
  392. MI->print(errs());
  393. llvm_unreachable("unknown operand type");
  394. case MachineOperand::MO_Register:
  395. // Ignore all implicit register operands.
  396. if (MO.isImplicit())
  397. return std::nullopt;
  398. return MCOperand::createReg(MO.getReg());
  399. case MachineOperand::MO_Immediate:
  400. return MCOperand::createImm(MO.getImm());
  401. case MachineOperand::MO_MachineBasicBlock:
  402. case MachineOperand::MO_GlobalAddress:
  403. case MachineOperand::MO_ExternalSymbol:
  404. return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
  405. case MachineOperand::MO_MCSymbol:
  406. return LowerSymbolOperand(MO, MO.getMCSymbol());
  407. case MachineOperand::MO_JumpTableIndex:
  408. return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
  409. case MachineOperand::MO_ConstantPoolIndex:
  410. return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
  411. case MachineOperand::MO_BlockAddress:
  412. return LowerSymbolOperand(
  413. MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
  414. case MachineOperand::MO_RegisterMask:
  415. // Ignore call clobbers.
  416. return std::nullopt;
  417. }
  418. }
  419. // Replace TAILJMP opcodes with their equivalent opcodes that have encoding
  420. // information.
  421. static unsigned convertTailJumpOpcode(unsigned Opcode) {
  422. switch (Opcode) {
  423. case X86::TAILJMPr:
  424. Opcode = X86::JMP32r;
  425. break;
  426. case X86::TAILJMPm:
  427. Opcode = X86::JMP32m;
  428. break;
  429. case X86::TAILJMPr64:
  430. Opcode = X86::JMP64r;
  431. break;
  432. case X86::TAILJMPm64:
  433. Opcode = X86::JMP64m;
  434. break;
  435. case X86::TAILJMPr64_REX:
  436. Opcode = X86::JMP64r_REX;
  437. break;
  438. case X86::TAILJMPm64_REX:
  439. Opcode = X86::JMP64m_REX;
  440. break;
  441. case X86::TAILJMPd:
  442. case X86::TAILJMPd64:
  443. Opcode = X86::JMP_1;
  444. break;
  445. case X86::TAILJMPd_CC:
  446. case X86::TAILJMPd64_CC:
  447. Opcode = X86::JCC_1;
  448. break;
  449. }
  450. return Opcode;
  451. }
  452. void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
  453. OutMI.setOpcode(MI->getOpcode());
  454. for (const MachineOperand &MO : MI->operands())
  455. if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
  456. OutMI.addOperand(*MaybeMCOp);
  457. // Handle a few special cases to eliminate operand modifiers.
  458. switch (OutMI.getOpcode()) {
  459. case X86::LEA64_32r:
  460. case X86::LEA64r:
  461. case X86::LEA16r:
  462. case X86::LEA32r:
  463. // LEA should have a segment register, but it must be empty.
  464. assert(OutMI.getNumOperands() == 1 + X86::AddrNumOperands &&
  465. "Unexpected # of LEA operands");
  466. assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
  467. "LEA has segment specified!");
  468. break;
  469. case X86::MULX32Hrr:
  470. case X86::MULX32Hrm:
  471. case X86::MULX64Hrr:
  472. case X86::MULX64Hrm: {
  473. // Turn into regular MULX by duplicating the destination.
  474. unsigned NewOpc;
  475. switch (OutMI.getOpcode()) {
  476. default: llvm_unreachable("Invalid opcode");
  477. case X86::MULX32Hrr: NewOpc = X86::MULX32rr; break;
  478. case X86::MULX32Hrm: NewOpc = X86::MULX32rm; break;
  479. case X86::MULX64Hrr: NewOpc = X86::MULX64rr; break;
  480. case X86::MULX64Hrm: NewOpc = X86::MULX64rm; break;
  481. }
  482. OutMI.setOpcode(NewOpc);
  483. // Duplicate the destination.
  484. unsigned DestReg = OutMI.getOperand(0).getReg();
  485. OutMI.insert(OutMI.begin(), MCOperand::createReg(DestReg));
  486. break;
  487. }
  488. // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
  489. // if one of the registers is extended, but other isn't.
  490. case X86::VMOVZPQILo2PQIrr:
  491. case X86::VMOVAPDrr:
  492. case X86::VMOVAPDYrr:
  493. case X86::VMOVAPSrr:
  494. case X86::VMOVAPSYrr:
  495. case X86::VMOVDQArr:
  496. case X86::VMOVDQAYrr:
  497. case X86::VMOVDQUrr:
  498. case X86::VMOVDQUYrr:
  499. case X86::VMOVUPDrr:
  500. case X86::VMOVUPDYrr:
  501. case X86::VMOVUPSrr:
  502. case X86::VMOVUPSYrr: {
  503. if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
  504. X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
  505. unsigned NewOpc;
  506. switch (OutMI.getOpcode()) {
  507. default: llvm_unreachable("Invalid opcode");
  508. case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break;
  509. case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
  510. case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
  511. case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
  512. case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
  513. case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
  514. case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
  515. case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
  516. case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
  517. case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
  518. case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
  519. case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
  520. case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
  521. }
  522. OutMI.setOpcode(NewOpc);
  523. }
  524. break;
  525. }
  526. case X86::VMOVSDrr:
  527. case X86::VMOVSSrr: {
  528. if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
  529. X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
  530. unsigned NewOpc;
  531. switch (OutMI.getOpcode()) {
  532. default: llvm_unreachable("Invalid opcode");
  533. case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
  534. case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
  535. }
  536. OutMI.setOpcode(NewOpc);
  537. }
  538. break;
  539. }
  540. case X86::VPCMPBZ128rmi: case X86::VPCMPBZ128rmik:
  541. case X86::VPCMPBZ128rri: case X86::VPCMPBZ128rrik:
  542. case X86::VPCMPBZ256rmi: case X86::VPCMPBZ256rmik:
  543. case X86::VPCMPBZ256rri: case X86::VPCMPBZ256rrik:
  544. case X86::VPCMPBZrmi: case X86::VPCMPBZrmik:
  545. case X86::VPCMPBZrri: case X86::VPCMPBZrrik:
  546. case X86::VPCMPDZ128rmi: case X86::VPCMPDZ128rmik:
  547. case X86::VPCMPDZ128rmib: case X86::VPCMPDZ128rmibk:
  548. case X86::VPCMPDZ128rri: case X86::VPCMPDZ128rrik:
  549. case X86::VPCMPDZ256rmi: case X86::VPCMPDZ256rmik:
  550. case X86::VPCMPDZ256rmib: case X86::VPCMPDZ256rmibk:
  551. case X86::VPCMPDZ256rri: case X86::VPCMPDZ256rrik:
  552. case X86::VPCMPDZrmi: case X86::VPCMPDZrmik:
  553. case X86::VPCMPDZrmib: case X86::VPCMPDZrmibk:
  554. case X86::VPCMPDZrri: case X86::VPCMPDZrrik:
  555. case X86::VPCMPQZ128rmi: case X86::VPCMPQZ128rmik:
  556. case X86::VPCMPQZ128rmib: case X86::VPCMPQZ128rmibk:
  557. case X86::VPCMPQZ128rri: case X86::VPCMPQZ128rrik:
  558. case X86::VPCMPQZ256rmi: case X86::VPCMPQZ256rmik:
  559. case X86::VPCMPQZ256rmib: case X86::VPCMPQZ256rmibk:
  560. case X86::VPCMPQZ256rri: case X86::VPCMPQZ256rrik:
  561. case X86::VPCMPQZrmi: case X86::VPCMPQZrmik:
  562. case X86::VPCMPQZrmib: case X86::VPCMPQZrmibk:
  563. case X86::VPCMPQZrri: case X86::VPCMPQZrrik:
  564. case X86::VPCMPWZ128rmi: case X86::VPCMPWZ128rmik:
  565. case X86::VPCMPWZ128rri: case X86::VPCMPWZ128rrik:
  566. case X86::VPCMPWZ256rmi: case X86::VPCMPWZ256rmik:
  567. case X86::VPCMPWZ256rri: case X86::VPCMPWZ256rrik:
  568. case X86::VPCMPWZrmi: case X86::VPCMPWZrmik:
  569. case X86::VPCMPWZrri: case X86::VPCMPWZrrik: {
  570. // Turn immediate 0 into the VPCMPEQ instruction.
  571. if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 0) {
  572. unsigned NewOpc;
  573. switch (OutMI.getOpcode()) {
  574. default: llvm_unreachable("Invalid opcode");
  575. case X86::VPCMPBZ128rmi: NewOpc = X86::VPCMPEQBZ128rm; break;
  576. case X86::VPCMPBZ128rmik: NewOpc = X86::VPCMPEQBZ128rmk; break;
  577. case X86::VPCMPBZ128rri: NewOpc = X86::VPCMPEQBZ128rr; break;
  578. case X86::VPCMPBZ128rrik: NewOpc = X86::VPCMPEQBZ128rrk; break;
  579. case X86::VPCMPBZ256rmi: NewOpc = X86::VPCMPEQBZ256rm; break;
  580. case X86::VPCMPBZ256rmik: NewOpc = X86::VPCMPEQBZ256rmk; break;
  581. case X86::VPCMPBZ256rri: NewOpc = X86::VPCMPEQBZ256rr; break;
  582. case X86::VPCMPBZ256rrik: NewOpc = X86::VPCMPEQBZ256rrk; break;
  583. case X86::VPCMPBZrmi: NewOpc = X86::VPCMPEQBZrm; break;
  584. case X86::VPCMPBZrmik: NewOpc = X86::VPCMPEQBZrmk; break;
  585. case X86::VPCMPBZrri: NewOpc = X86::VPCMPEQBZrr; break;
  586. case X86::VPCMPBZrrik: NewOpc = X86::VPCMPEQBZrrk; break;
  587. case X86::VPCMPDZ128rmi: NewOpc = X86::VPCMPEQDZ128rm; break;
  588. case X86::VPCMPDZ128rmib: NewOpc = X86::VPCMPEQDZ128rmb; break;
  589. case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPEQDZ128rmbk; break;
  590. case X86::VPCMPDZ128rmik: NewOpc = X86::VPCMPEQDZ128rmk; break;
  591. case X86::VPCMPDZ128rri: NewOpc = X86::VPCMPEQDZ128rr; break;
  592. case X86::VPCMPDZ128rrik: NewOpc = X86::VPCMPEQDZ128rrk; break;
  593. case X86::VPCMPDZ256rmi: NewOpc = X86::VPCMPEQDZ256rm; break;
  594. case X86::VPCMPDZ256rmib: NewOpc = X86::VPCMPEQDZ256rmb; break;
  595. case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPEQDZ256rmbk; break;
  596. case X86::VPCMPDZ256rmik: NewOpc = X86::VPCMPEQDZ256rmk; break;
  597. case X86::VPCMPDZ256rri: NewOpc = X86::VPCMPEQDZ256rr; break;
  598. case X86::VPCMPDZ256rrik: NewOpc = X86::VPCMPEQDZ256rrk; break;
  599. case X86::VPCMPDZrmi: NewOpc = X86::VPCMPEQDZrm; break;
  600. case X86::VPCMPDZrmib: NewOpc = X86::VPCMPEQDZrmb; break;
  601. case X86::VPCMPDZrmibk: NewOpc = X86::VPCMPEQDZrmbk; break;
  602. case X86::VPCMPDZrmik: NewOpc = X86::VPCMPEQDZrmk; break;
  603. case X86::VPCMPDZrri: NewOpc = X86::VPCMPEQDZrr; break;
  604. case X86::VPCMPDZrrik: NewOpc = X86::VPCMPEQDZrrk; break;
  605. case X86::VPCMPQZ128rmi: NewOpc = X86::VPCMPEQQZ128rm; break;
  606. case X86::VPCMPQZ128rmib: NewOpc = X86::VPCMPEQQZ128rmb; break;
  607. case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPEQQZ128rmbk; break;
  608. case X86::VPCMPQZ128rmik: NewOpc = X86::VPCMPEQQZ128rmk; break;
  609. case X86::VPCMPQZ128rri: NewOpc = X86::VPCMPEQQZ128rr; break;
  610. case X86::VPCMPQZ128rrik: NewOpc = X86::VPCMPEQQZ128rrk; break;
  611. case X86::VPCMPQZ256rmi: NewOpc = X86::VPCMPEQQZ256rm; break;
  612. case X86::VPCMPQZ256rmib: NewOpc = X86::VPCMPEQQZ256rmb; break;
  613. case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPEQQZ256rmbk; break;
  614. case X86::VPCMPQZ256rmik: NewOpc = X86::VPCMPEQQZ256rmk; break;
  615. case X86::VPCMPQZ256rri: NewOpc = X86::VPCMPEQQZ256rr; break;
  616. case X86::VPCMPQZ256rrik: NewOpc = X86::VPCMPEQQZ256rrk; break;
  617. case X86::VPCMPQZrmi: NewOpc = X86::VPCMPEQQZrm; break;
  618. case X86::VPCMPQZrmib: NewOpc = X86::VPCMPEQQZrmb; break;
  619. case X86::VPCMPQZrmibk: NewOpc = X86::VPCMPEQQZrmbk; break;
  620. case X86::VPCMPQZrmik: NewOpc = X86::VPCMPEQQZrmk; break;
  621. case X86::VPCMPQZrri: NewOpc = X86::VPCMPEQQZrr; break;
  622. case X86::VPCMPQZrrik: NewOpc = X86::VPCMPEQQZrrk; break;
  623. case X86::VPCMPWZ128rmi: NewOpc = X86::VPCMPEQWZ128rm; break;
  624. case X86::VPCMPWZ128rmik: NewOpc = X86::VPCMPEQWZ128rmk; break;
  625. case X86::VPCMPWZ128rri: NewOpc = X86::VPCMPEQWZ128rr; break;
  626. case X86::VPCMPWZ128rrik: NewOpc = X86::VPCMPEQWZ128rrk; break;
  627. case X86::VPCMPWZ256rmi: NewOpc = X86::VPCMPEQWZ256rm; break;
  628. case X86::VPCMPWZ256rmik: NewOpc = X86::VPCMPEQWZ256rmk; break;
  629. case X86::VPCMPWZ256rri: NewOpc = X86::VPCMPEQWZ256rr; break;
  630. case X86::VPCMPWZ256rrik: NewOpc = X86::VPCMPEQWZ256rrk; break;
  631. case X86::VPCMPWZrmi: NewOpc = X86::VPCMPEQWZrm; break;
  632. case X86::VPCMPWZrmik: NewOpc = X86::VPCMPEQWZrmk; break;
  633. case X86::VPCMPWZrri: NewOpc = X86::VPCMPEQWZrr; break;
  634. case X86::VPCMPWZrrik: NewOpc = X86::VPCMPEQWZrrk; break;
  635. }
  636. OutMI.setOpcode(NewOpc);
  637. OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
  638. break;
  639. }
  640. // Turn immediate 6 into the VPCMPGT instruction.
  641. if (OutMI.getOperand(OutMI.getNumOperands() - 1).getImm() == 6) {
  642. unsigned NewOpc;
  643. switch (OutMI.getOpcode()) {
  644. default: llvm_unreachable("Invalid opcode");
  645. case X86::VPCMPBZ128rmi: NewOpc = X86::VPCMPGTBZ128rm; break;
  646. case X86::VPCMPBZ128rmik: NewOpc = X86::VPCMPGTBZ128rmk; break;
  647. case X86::VPCMPBZ128rri: NewOpc = X86::VPCMPGTBZ128rr; break;
  648. case X86::VPCMPBZ128rrik: NewOpc = X86::VPCMPGTBZ128rrk; break;
  649. case X86::VPCMPBZ256rmi: NewOpc = X86::VPCMPGTBZ256rm; break;
  650. case X86::VPCMPBZ256rmik: NewOpc = X86::VPCMPGTBZ256rmk; break;
  651. case X86::VPCMPBZ256rri: NewOpc = X86::VPCMPGTBZ256rr; break;
  652. case X86::VPCMPBZ256rrik: NewOpc = X86::VPCMPGTBZ256rrk; break;
  653. case X86::VPCMPBZrmi: NewOpc = X86::VPCMPGTBZrm; break;
  654. case X86::VPCMPBZrmik: NewOpc = X86::VPCMPGTBZrmk; break;
  655. case X86::VPCMPBZrri: NewOpc = X86::VPCMPGTBZrr; break;
  656. case X86::VPCMPBZrrik: NewOpc = X86::VPCMPGTBZrrk; break;
  657. case X86::VPCMPDZ128rmi: NewOpc = X86::VPCMPGTDZ128rm; break;
  658. case X86::VPCMPDZ128rmib: NewOpc = X86::VPCMPGTDZ128rmb; break;
  659. case X86::VPCMPDZ128rmibk: NewOpc = X86::VPCMPGTDZ128rmbk; break;
  660. case X86::VPCMPDZ128rmik: NewOpc = X86::VPCMPGTDZ128rmk; break;
  661. case X86::VPCMPDZ128rri: NewOpc = X86::VPCMPGTDZ128rr; break;
  662. case X86::VPCMPDZ128rrik: NewOpc = X86::VPCMPGTDZ128rrk; break;
  663. case X86::VPCMPDZ256rmi: NewOpc = X86::VPCMPGTDZ256rm; break;
  664. case X86::VPCMPDZ256rmib: NewOpc = X86::VPCMPGTDZ256rmb; break;
  665. case X86::VPCMPDZ256rmibk: NewOpc = X86::VPCMPGTDZ256rmbk; break;
  666. case X86::VPCMPDZ256rmik: NewOpc = X86::VPCMPGTDZ256rmk; break;
  667. case X86::VPCMPDZ256rri: NewOpc = X86::VPCMPGTDZ256rr; break;
  668. case X86::VPCMPDZ256rrik: NewOpc = X86::VPCMPGTDZ256rrk; break;
  669. case X86::VPCMPDZrmi: NewOpc = X86::VPCMPGTDZrm; break;
  670. case X86::VPCMPDZrmib: NewOpc = X86::VPCMPGTDZrmb; break;
  671. case X86::VPCMPDZrmibk: NewOpc = X86::VPCMPGTDZrmbk; break;
  672. case X86::VPCMPDZrmik: NewOpc = X86::VPCMPGTDZrmk; break;
  673. case X86::VPCMPDZrri: NewOpc = X86::VPCMPGTDZrr; break;
  674. case X86::VPCMPDZrrik: NewOpc = X86::VPCMPGTDZrrk; break;
  675. case X86::VPCMPQZ128rmi: NewOpc = X86::VPCMPGTQZ128rm; break;
  676. case X86::VPCMPQZ128rmib: NewOpc = X86::VPCMPGTQZ128rmb; break;
  677. case X86::VPCMPQZ128rmibk: NewOpc = X86::VPCMPGTQZ128rmbk; break;
  678. case X86::VPCMPQZ128rmik: NewOpc = X86::VPCMPGTQZ128rmk; break;
  679. case X86::VPCMPQZ128rri: NewOpc = X86::VPCMPGTQZ128rr; break;
  680. case X86::VPCMPQZ128rrik: NewOpc = X86::VPCMPGTQZ128rrk; break;
  681. case X86::VPCMPQZ256rmi: NewOpc = X86::VPCMPGTQZ256rm; break;
  682. case X86::VPCMPQZ256rmib: NewOpc = X86::VPCMPGTQZ256rmb; break;
  683. case X86::VPCMPQZ256rmibk: NewOpc = X86::VPCMPGTQZ256rmbk; break;
  684. case X86::VPCMPQZ256rmik: NewOpc = X86::VPCMPGTQZ256rmk; break;
  685. case X86::VPCMPQZ256rri: NewOpc = X86::VPCMPGTQZ256rr; break;
  686. case X86::VPCMPQZ256rrik: NewOpc = X86::VPCMPGTQZ256rrk; break;
  687. case X86::VPCMPQZrmi: NewOpc = X86::VPCMPGTQZrm; break;
  688. case X86::VPCMPQZrmib: NewOpc = X86::VPCMPGTQZrmb; break;
  689. case X86::VPCMPQZrmibk: NewOpc = X86::VPCMPGTQZrmbk; break;
  690. case X86::VPCMPQZrmik: NewOpc = X86::VPCMPGTQZrmk; break;
  691. case X86::VPCMPQZrri: NewOpc = X86::VPCMPGTQZrr; break;
  692. case X86::VPCMPQZrrik: NewOpc = X86::VPCMPGTQZrrk; break;
  693. case X86::VPCMPWZ128rmi: NewOpc = X86::VPCMPGTWZ128rm; break;
  694. case X86::VPCMPWZ128rmik: NewOpc = X86::VPCMPGTWZ128rmk; break;
  695. case X86::VPCMPWZ128rri: NewOpc = X86::VPCMPGTWZ128rr; break;
  696. case X86::VPCMPWZ128rrik: NewOpc = X86::VPCMPGTWZ128rrk; break;
  697. case X86::VPCMPWZ256rmi: NewOpc = X86::VPCMPGTWZ256rm; break;
  698. case X86::VPCMPWZ256rmik: NewOpc = X86::VPCMPGTWZ256rmk; break;
  699. case X86::VPCMPWZ256rri: NewOpc = X86::VPCMPGTWZ256rr; break;
  700. case X86::VPCMPWZ256rrik: NewOpc = X86::VPCMPGTWZ256rrk; break;
  701. case X86::VPCMPWZrmi: NewOpc = X86::VPCMPGTWZrm; break;
  702. case X86::VPCMPWZrmik: NewOpc = X86::VPCMPGTWZrmk; break;
  703. case X86::VPCMPWZrri: NewOpc = X86::VPCMPGTWZrr; break;
  704. case X86::VPCMPWZrrik: NewOpc = X86::VPCMPGTWZrrk; break;
  705. }
  706. OutMI.setOpcode(NewOpc);
  707. OutMI.erase(&OutMI.getOperand(OutMI.getNumOperands() - 1));
  708. break;
  709. }
  710. break;
  711. }
  712. // CALL64r, CALL64pcrel32 - These instructions used to have
  713. // register inputs modeled as normal uses instead of implicit uses. As such,
  714. // they we used to truncate off all but the first operand (the callee). This
  715. // issue seems to have been fixed at some point. This assert verifies that.
  716. case X86::CALL64r:
  717. case X86::CALL64pcrel32:
  718. assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
  719. break;
  720. case X86::EH_RETURN:
  721. case X86::EH_RETURN64: {
  722. OutMI = MCInst();
  723. OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
  724. break;
  725. }
  726. case X86::CLEANUPRET: {
  727. // Replace CLEANUPRET with the appropriate RET.
  728. OutMI = MCInst();
  729. OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
  730. break;
  731. }
  732. case X86::CATCHRET: {
  733. // Replace CATCHRET with the appropriate RET.
  734. const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
  735. unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
  736. OutMI = MCInst();
  737. OutMI.setOpcode(getRetOpcode(Subtarget));
  738. OutMI.addOperand(MCOperand::createReg(ReturnReg));
  739. break;
  740. }
  741. // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
  742. // instruction.
  743. case X86::TAILJMPr:
  744. case X86::TAILJMPr64:
  745. case X86::TAILJMPr64_REX:
  746. case X86::TAILJMPd:
  747. case X86::TAILJMPd64:
  748. assert(OutMI.getNumOperands() == 1 && "Unexpected number of operands!");
  749. OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
  750. break;
  751. case X86::TAILJMPd_CC:
  752. case X86::TAILJMPd64_CC:
  753. assert(OutMI.getNumOperands() == 2 && "Unexpected number of operands!");
  754. OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
  755. break;
  756. case X86::TAILJMPm:
  757. case X86::TAILJMPm64:
  758. case X86::TAILJMPm64_REX:
  759. assert(OutMI.getNumOperands() == X86::AddrNumOperands &&
  760. "Unexpected number of operands!");
  761. OutMI.setOpcode(convertTailJumpOpcode(OutMI.getOpcode()));
  762. break;
  763. case X86::DEC16r:
  764. case X86::DEC32r:
  765. case X86::INC16r:
  766. case X86::INC32r:
  767. // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
  768. if (!AsmPrinter.getSubtarget().is64Bit()) {
  769. unsigned Opcode;
  770. switch (OutMI.getOpcode()) {
  771. default: llvm_unreachable("Invalid opcode");
  772. case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
  773. case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
  774. case X86::INC16r: Opcode = X86::INC16r_alt; break;
  775. case X86::INC32r: Opcode = X86::INC32r_alt; break;
  776. }
  777. OutMI.setOpcode(Opcode);
  778. }
  779. break;
  780. // We don't currently select the correct instruction form for instructions
  781. // which have a short %eax, etc. form. Handle this by custom lowering, for
  782. // now.
  783. //
  784. // Note, we are currently not handling the following instructions:
  785. // MOV64ao8, MOV64o8a
  786. // XCHG16ar, XCHG32ar, XCHG64ar
  787. case X86::MOV8mr_NOREX:
  788. case X86::MOV8mr:
  789. case X86::MOV8rm_NOREX:
  790. case X86::MOV8rm:
  791. case X86::MOV16mr:
  792. case X86::MOV16rm:
  793. case X86::MOV32mr:
  794. case X86::MOV32rm: {
  795. unsigned NewOpc;
  796. switch (OutMI.getOpcode()) {
  797. default: llvm_unreachable("Invalid opcode");
  798. case X86::MOV8mr_NOREX:
  799. case X86::MOV8mr: NewOpc = X86::MOV8o32a; break;
  800. case X86::MOV8rm_NOREX:
  801. case X86::MOV8rm: NewOpc = X86::MOV8ao32; break;
  802. case X86::MOV16mr: NewOpc = X86::MOV16o32a; break;
  803. case X86::MOV16rm: NewOpc = X86::MOV16ao32; break;
  804. case X86::MOV32mr: NewOpc = X86::MOV32o32a; break;
  805. case X86::MOV32rm: NewOpc = X86::MOV32ao32; break;
  806. }
  807. SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
  808. break;
  809. }
  810. case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
  811. case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
  812. case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
  813. case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
  814. case X86::OR8ri: case X86::OR16ri: case X86::OR32ri: case X86::OR64ri32:
  815. case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
  816. case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
  817. case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
  818. case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
  819. unsigned NewOpc;
  820. switch (OutMI.getOpcode()) {
  821. default: llvm_unreachable("Invalid opcode");
  822. case X86::ADC8ri: NewOpc = X86::ADC8i8; break;
  823. case X86::ADC16ri: NewOpc = X86::ADC16i16; break;
  824. case X86::ADC32ri: NewOpc = X86::ADC32i32; break;
  825. case X86::ADC64ri32: NewOpc = X86::ADC64i32; break;
  826. case X86::ADD8ri: NewOpc = X86::ADD8i8; break;
  827. case X86::ADD16ri: NewOpc = X86::ADD16i16; break;
  828. case X86::ADD32ri: NewOpc = X86::ADD32i32; break;
  829. case X86::ADD64ri32: NewOpc = X86::ADD64i32; break;
  830. case X86::AND8ri: NewOpc = X86::AND8i8; break;
  831. case X86::AND16ri: NewOpc = X86::AND16i16; break;
  832. case X86::AND32ri: NewOpc = X86::AND32i32; break;
  833. case X86::AND64ri32: NewOpc = X86::AND64i32; break;
  834. case X86::CMP8ri: NewOpc = X86::CMP8i8; break;
  835. case X86::CMP16ri: NewOpc = X86::CMP16i16; break;
  836. case X86::CMP32ri: NewOpc = X86::CMP32i32; break;
  837. case X86::CMP64ri32: NewOpc = X86::CMP64i32; break;
  838. case X86::OR8ri: NewOpc = X86::OR8i8; break;
  839. case X86::OR16ri: NewOpc = X86::OR16i16; break;
  840. case X86::OR32ri: NewOpc = X86::OR32i32; break;
  841. case X86::OR64ri32: NewOpc = X86::OR64i32; break;
  842. case X86::SBB8ri: NewOpc = X86::SBB8i8; break;
  843. case X86::SBB16ri: NewOpc = X86::SBB16i16; break;
  844. case X86::SBB32ri: NewOpc = X86::SBB32i32; break;
  845. case X86::SBB64ri32: NewOpc = X86::SBB64i32; break;
  846. case X86::SUB8ri: NewOpc = X86::SUB8i8; break;
  847. case X86::SUB16ri: NewOpc = X86::SUB16i16; break;
  848. case X86::SUB32ri: NewOpc = X86::SUB32i32; break;
  849. case X86::SUB64ri32: NewOpc = X86::SUB64i32; break;
  850. case X86::TEST8ri: NewOpc = X86::TEST8i8; break;
  851. case X86::TEST16ri: NewOpc = X86::TEST16i16; break;
  852. case X86::TEST32ri: NewOpc = X86::TEST32i32; break;
  853. case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
  854. case X86::XOR8ri: NewOpc = X86::XOR8i8; break;
  855. case X86::XOR16ri: NewOpc = X86::XOR16i16; break;
  856. case X86::XOR32ri: NewOpc = X86::XOR32i32; break;
  857. case X86::XOR64ri32: NewOpc = X86::XOR64i32; break;
  858. }
  859. SimplifyShortImmForm(OutMI, NewOpc);
  860. break;
  861. }
  862. // Try to shrink some forms of movsx.
  863. case X86::MOVSX16rr8:
  864. case X86::MOVSX32rr16:
  865. case X86::MOVSX64rr32:
  866. SimplifyMOVSX(OutMI);
  867. break;
  868. case X86::VCMPPDrri:
  869. case X86::VCMPPDYrri:
  870. case X86::VCMPPSrri:
  871. case X86::VCMPPSYrri:
  872. case X86::VCMPSDrr:
  873. case X86::VCMPSSrr: {
  874. // Swap the operands if it will enable a 2 byte VEX encoding.
  875. // FIXME: Change the immediate to improve opportunities?
  876. if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg()) &&
  877. X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
  878. unsigned Imm = MI->getOperand(3).getImm() & 0x7;
  879. switch (Imm) {
  880. default: break;
  881. case 0x00: // EQUAL
  882. case 0x03: // UNORDERED
  883. case 0x04: // NOT EQUAL
  884. case 0x07: // ORDERED
  885. std::swap(OutMI.getOperand(1), OutMI.getOperand(2));
  886. break;
  887. }
  888. }
  889. break;
  890. }
  891. case X86::VMOVHLPSrr:
  892. case X86::VUNPCKHPDrr:
  893. // These are not truly commutable so hide them from the default case.
  894. break;
  895. case X86::MASKMOVDQU:
  896. case X86::VMASKMOVDQU:
  897. if (AsmPrinter.getSubtarget().is64Bit())
  898. OutMI.setFlags(X86::IP_HAS_AD_SIZE);
  899. break;
  900. default: {
  901. // If the instruction is a commutable arithmetic instruction we might be
  902. // able to commute the operands to get a 2 byte VEX prefix.
  903. uint64_t TSFlags = MI->getDesc().TSFlags;
  904. if (MI->getDesc().isCommutable() &&
  905. (TSFlags & X86II::EncodingMask) == X86II::VEX &&
  906. (TSFlags & X86II::OpMapMask) == X86II::TB &&
  907. (TSFlags & X86II::FormMask) == X86II::MRMSrcReg &&
  908. !(TSFlags & X86II::VEX_W) && (TSFlags & X86II::VEX_4V) &&
  909. OutMI.getNumOperands() == 3) {
  910. if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg()) &&
  911. X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg()))
  912. std::swap(OutMI.getOperand(1), OutMI.getOperand(2));
  913. }
  914. // Add an REP prefix to BSF instructions so that new processors can
  915. // recognize as TZCNT, which has better performance than BSF.
  916. if (X86::isBSF(OutMI.getOpcode()) && !MF.getFunction().hasOptSize()) {
  917. // BSF and TZCNT have different interpretations on ZF bit. So make sure
  918. // it won't be used later.
  919. const MachineOperand *FlagDef = MI->findRegisterDefOperand(X86::EFLAGS);
  920. if (FlagDef && FlagDef->isDead())
  921. OutMI.setFlags(X86::IP_HAS_REPEAT);
  922. }
  923. break;
  924. }
  925. }
  926. }
  927. void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
  928. const MachineInstr &MI) {
  929. NoAutoPaddingScope NoPadScope(*OutStreamer);
  930. bool Is64Bits = MI.getOpcode() != X86::TLS_addr32 &&
  931. MI.getOpcode() != X86::TLS_base_addr32;
  932. bool Is64BitsLP64 = MI.getOpcode() == X86::TLS_addr64 ||
  933. MI.getOpcode() == X86::TLS_base_addr64;
  934. MCContext &Ctx = OutStreamer->getContext();
  935. MCSymbolRefExpr::VariantKind SRVK;
  936. switch (MI.getOpcode()) {
  937. case X86::TLS_addr32:
  938. case X86::TLS_addr64:
  939. case X86::TLS_addrX32:
  940. SRVK = MCSymbolRefExpr::VK_TLSGD;
  941. break;
  942. case X86::TLS_base_addr32:
  943. SRVK = MCSymbolRefExpr::VK_TLSLDM;
  944. break;
  945. case X86::TLS_base_addr64:
  946. case X86::TLS_base_addrX32:
  947. SRVK = MCSymbolRefExpr::VK_TLSLD;
  948. break;
  949. default:
  950. llvm_unreachable("unexpected opcode");
  951. }
  952. const MCSymbolRefExpr *Sym = MCSymbolRefExpr::create(
  953. MCInstLowering.GetSymbolFromOperand(MI.getOperand(3)), SRVK, Ctx);
  954. // As of binutils 2.32, ld has a bogus TLS relaxation error when the GD/LD
  955. // code sequence using R_X86_64_GOTPCREL (instead of R_X86_64_GOTPCRELX) is
  956. // attempted to be relaxed to IE/LE (binutils PR24784). Work around the bug by
  957. // only using GOT when GOTPCRELX is enabled.
  958. // TODO Delete the workaround when GOTPCRELX becomes commonplace.
  959. bool UseGot = MMI->getModule()->getRtLibUseGOT() &&
  960. Ctx.getAsmInfo()->canRelaxRelocations();
  961. if (Is64Bits) {
  962. bool NeedsPadding = SRVK == MCSymbolRefExpr::VK_TLSGD;
  963. if (NeedsPadding && Is64BitsLP64)
  964. EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
  965. EmitAndCountInstruction(MCInstBuilder(X86::LEA64r)
  966. .addReg(X86::RDI)
  967. .addReg(X86::RIP)
  968. .addImm(1)
  969. .addReg(0)
  970. .addExpr(Sym)
  971. .addReg(0));
  972. const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("__tls_get_addr");
  973. if (NeedsPadding) {
  974. if (!UseGot)
  975. EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
  976. EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
  977. EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
  978. }
  979. if (UseGot) {
  980. const MCExpr *Expr = MCSymbolRefExpr::create(
  981. TlsGetAddr, MCSymbolRefExpr::VK_GOTPCREL, Ctx);
  982. EmitAndCountInstruction(MCInstBuilder(X86::CALL64m)
  983. .addReg(X86::RIP)
  984. .addImm(1)
  985. .addReg(0)
  986. .addExpr(Expr)
  987. .addReg(0));
  988. } else {
  989. EmitAndCountInstruction(
  990. MCInstBuilder(X86::CALL64pcrel32)
  991. .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
  992. MCSymbolRefExpr::VK_PLT, Ctx)));
  993. }
  994. } else {
  995. if (SRVK == MCSymbolRefExpr::VK_TLSGD && !UseGot) {
  996. EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
  997. .addReg(X86::EAX)
  998. .addReg(0)
  999. .addImm(1)
  1000. .addReg(X86::EBX)
  1001. .addExpr(Sym)
  1002. .addReg(0));
  1003. } else {
  1004. EmitAndCountInstruction(MCInstBuilder(X86::LEA32r)
  1005. .addReg(X86::EAX)
  1006. .addReg(X86::EBX)
  1007. .addImm(1)
  1008. .addReg(0)
  1009. .addExpr(Sym)
  1010. .addReg(0));
  1011. }
  1012. const MCSymbol *TlsGetAddr = Ctx.getOrCreateSymbol("___tls_get_addr");
  1013. if (UseGot) {
  1014. const MCExpr *Expr =
  1015. MCSymbolRefExpr::create(TlsGetAddr, MCSymbolRefExpr::VK_GOT, Ctx);
  1016. EmitAndCountInstruction(MCInstBuilder(X86::CALL32m)
  1017. .addReg(X86::EBX)
  1018. .addImm(1)
  1019. .addReg(0)
  1020. .addExpr(Expr)
  1021. .addReg(0));
  1022. } else {
  1023. EmitAndCountInstruction(
  1024. MCInstBuilder(X86::CALLpcrel32)
  1025. .addExpr(MCSymbolRefExpr::create(TlsGetAddr,
  1026. MCSymbolRefExpr::VK_PLT, Ctx)));
  1027. }
  1028. }
  1029. }
  1030. /// Emit the largest nop instruction smaller than or equal to \p NumBytes
  1031. /// bytes. Return the size of nop emitted.
  1032. static unsigned emitNop(MCStreamer &OS, unsigned NumBytes,
  1033. const X86Subtarget *Subtarget) {
  1034. // Determine the longest nop which can be efficiently decoded for the given
  1035. // target cpu. 15-bytes is the longest single NOP instruction, but some
  1036. // platforms can't decode the longest forms efficiently.
  1037. unsigned MaxNopLength = 1;
  1038. if (Subtarget->is64Bit()) {
  1039. // FIXME: We can use NOOPL on 32-bit targets with FeatureNOPL, but the
  1040. // IndexReg/BaseReg below need to be updated.
  1041. if (Subtarget->hasFeature(X86::TuningFast7ByteNOP))
  1042. MaxNopLength = 7;
  1043. else if (Subtarget->hasFeature(X86::TuningFast15ByteNOP))
  1044. MaxNopLength = 15;
  1045. else if (Subtarget->hasFeature(X86::TuningFast11ByteNOP))
  1046. MaxNopLength = 11;
  1047. else
  1048. MaxNopLength = 10;
  1049. } if (Subtarget->is32Bit())
  1050. MaxNopLength = 2;
  1051. // Cap a single nop emission at the profitable value for the target
  1052. NumBytes = std::min(NumBytes, MaxNopLength);
  1053. unsigned NopSize;
  1054. unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
  1055. IndexReg = Displacement = SegmentReg = 0;
  1056. BaseReg = X86::RAX;
  1057. ScaleVal = 1;
  1058. switch (NumBytes) {
  1059. case 0:
  1060. llvm_unreachable("Zero nops?");
  1061. break;
  1062. case 1:
  1063. NopSize = 1;
  1064. Opc = X86::NOOP;
  1065. break;
  1066. case 2:
  1067. NopSize = 2;
  1068. Opc = X86::XCHG16ar;
  1069. break;
  1070. case 3:
  1071. NopSize = 3;
  1072. Opc = X86::NOOPL;
  1073. break;
  1074. case 4:
  1075. NopSize = 4;
  1076. Opc = X86::NOOPL;
  1077. Displacement = 8;
  1078. break;
  1079. case 5:
  1080. NopSize = 5;
  1081. Opc = X86::NOOPL;
  1082. Displacement = 8;
  1083. IndexReg = X86::RAX;
  1084. break;
  1085. case 6:
  1086. NopSize = 6;
  1087. Opc = X86::NOOPW;
  1088. Displacement = 8;
  1089. IndexReg = X86::RAX;
  1090. break;
  1091. case 7:
  1092. NopSize = 7;
  1093. Opc = X86::NOOPL;
  1094. Displacement = 512;
  1095. break;
  1096. case 8:
  1097. NopSize = 8;
  1098. Opc = X86::NOOPL;
  1099. Displacement = 512;
  1100. IndexReg = X86::RAX;
  1101. break;
  1102. case 9:
  1103. NopSize = 9;
  1104. Opc = X86::NOOPW;
  1105. Displacement = 512;
  1106. IndexReg = X86::RAX;
  1107. break;
  1108. default:
  1109. NopSize = 10;
  1110. Opc = X86::NOOPW;
  1111. Displacement = 512;
  1112. IndexReg = X86::RAX;
  1113. SegmentReg = X86::CS;
  1114. break;
  1115. }
  1116. unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
  1117. NopSize += NumPrefixes;
  1118. for (unsigned i = 0; i != NumPrefixes; ++i)
  1119. OS.emitBytes("\x66");
  1120. switch (Opc) {
  1121. default: llvm_unreachable("Unexpected opcode");
  1122. case X86::NOOP:
  1123. OS.emitInstruction(MCInstBuilder(Opc), *Subtarget);
  1124. break;
  1125. case X86::XCHG16ar:
  1126. OS.emitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX),
  1127. *Subtarget);
  1128. break;
  1129. case X86::NOOPL:
  1130. case X86::NOOPW:
  1131. OS.emitInstruction(MCInstBuilder(Opc)
  1132. .addReg(BaseReg)
  1133. .addImm(ScaleVal)
  1134. .addReg(IndexReg)
  1135. .addImm(Displacement)
  1136. .addReg(SegmentReg),
  1137. *Subtarget);
  1138. break;
  1139. }
  1140. assert(NopSize <= NumBytes && "We overemitted?");
  1141. return NopSize;
  1142. }
  1143. /// Emit the optimal amount of multi-byte nops on X86.
  1144. static void emitX86Nops(MCStreamer &OS, unsigned NumBytes,
  1145. const X86Subtarget *Subtarget) {
  1146. unsigned NopsToEmit = NumBytes;
  1147. (void)NopsToEmit;
  1148. while (NumBytes) {
  1149. NumBytes -= emitNop(OS, NumBytes, Subtarget);
  1150. assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
  1151. }
  1152. }
  1153. void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
  1154. X86MCInstLower &MCIL) {
  1155. assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
  1156. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1157. StatepointOpers SOpers(&MI);
  1158. if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
  1159. emitX86Nops(*OutStreamer, PatchBytes, Subtarget);
  1160. } else {
  1161. // Lower call target and choose correct opcode
  1162. const MachineOperand &CallTarget = SOpers.getCallTarget();
  1163. MCOperand CallTargetMCOp;
  1164. unsigned CallOpcode;
  1165. switch (CallTarget.getType()) {
  1166. case MachineOperand::MO_GlobalAddress:
  1167. case MachineOperand::MO_ExternalSymbol:
  1168. CallTargetMCOp = MCIL.LowerSymbolOperand(
  1169. CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
  1170. CallOpcode = X86::CALL64pcrel32;
  1171. // Currently, we only support relative addressing with statepoints.
  1172. // Otherwise, we'll need a scratch register to hold the target
  1173. // address. You'll fail asserts during load & relocation if this
  1174. // symbol is to far away. (TODO: support non-relative addressing)
  1175. break;
  1176. case MachineOperand::MO_Immediate:
  1177. CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
  1178. CallOpcode = X86::CALL64pcrel32;
  1179. // Currently, we only support relative addressing with statepoints.
  1180. // Otherwise, we'll need a scratch register to hold the target
  1181. // immediate. You'll fail asserts during load & relocation if this
  1182. // address is to far away. (TODO: support non-relative addressing)
  1183. break;
  1184. case MachineOperand::MO_Register:
  1185. // FIXME: Add retpoline support and remove this.
  1186. if (Subtarget->useIndirectThunkCalls())
  1187. report_fatal_error("Lowering register statepoints with thunks not "
  1188. "yet implemented.");
  1189. CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
  1190. CallOpcode = X86::CALL64r;
  1191. break;
  1192. default:
  1193. llvm_unreachable("Unsupported operand type in statepoint call target");
  1194. break;
  1195. }
  1196. // Emit call
  1197. MCInst CallInst;
  1198. CallInst.setOpcode(CallOpcode);
  1199. CallInst.addOperand(CallTargetMCOp);
  1200. OutStreamer->emitInstruction(CallInst, getSubtargetInfo());
  1201. }
  1202. // Record our statepoint node in the same section used by STACKMAP
  1203. // and PATCHPOINT
  1204. auto &Ctx = OutStreamer->getContext();
  1205. MCSymbol *MILabel = Ctx.createTempSymbol();
  1206. OutStreamer->emitLabel(MILabel);
  1207. SM.recordStatepoint(*MILabel, MI);
  1208. }
  1209. void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
  1210. X86MCInstLower &MCIL) {
  1211. // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
  1212. // <opcode>, <operands>
  1213. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1214. Register DefRegister = FaultingMI.getOperand(0).getReg();
  1215. FaultMaps::FaultKind FK =
  1216. static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
  1217. MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
  1218. unsigned Opcode = FaultingMI.getOperand(3).getImm();
  1219. unsigned OperandsBeginIdx = 4;
  1220. auto &Ctx = OutStreamer->getContext();
  1221. MCSymbol *FaultingLabel = Ctx.createTempSymbol();
  1222. OutStreamer->emitLabel(FaultingLabel);
  1223. assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
  1224. FM.recordFaultingOp(FK, FaultingLabel, HandlerLabel);
  1225. MCInst MI;
  1226. MI.setOpcode(Opcode);
  1227. if (DefRegister != X86::NoRegister)
  1228. MI.addOperand(MCOperand::createReg(DefRegister));
  1229. for (const MachineOperand &MO :
  1230. llvm::drop_begin(FaultingMI.operands(), OperandsBeginIdx))
  1231. if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, MO))
  1232. MI.addOperand(*MaybeOperand);
  1233. OutStreamer->AddComment("on-fault: " + HandlerLabel->getName());
  1234. OutStreamer->emitInstruction(MI, getSubtargetInfo());
  1235. }
  1236. void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
  1237. X86MCInstLower &MCIL) {
  1238. bool Is64Bits = Subtarget->is64Bit();
  1239. MCContext &Ctx = OutStreamer->getContext();
  1240. MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
  1241. const MCSymbolRefExpr *Op =
  1242. MCSymbolRefExpr::create(fentry, MCSymbolRefExpr::VK_None, Ctx);
  1243. EmitAndCountInstruction(
  1244. MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
  1245. .addExpr(Op));
  1246. }
  1247. void X86AsmPrinter::LowerKCFI_CHECK(const MachineInstr &MI) {
  1248. assert(std::next(MI.getIterator())->isCall() &&
  1249. "KCFI_CHECK not followed by a call instruction");
  1250. // Adjust the offset for patchable-function-prefix. X86InstrInfo::getNop()
  1251. // returns a 1-byte X86::NOOP, which means the offset is the same in
  1252. // bytes. This assumes that patchable-function-prefix is the same for all
  1253. // functions.
  1254. const MachineFunction &MF = *MI.getMF();
  1255. int64_t PrefixNops = 0;
  1256. (void)MF.getFunction()
  1257. .getFnAttribute("patchable-function-prefix")
  1258. .getValueAsString()
  1259. .getAsInteger(10, PrefixNops);
  1260. // KCFI allows indirect calls to any location that's preceded by a valid
  1261. // type identifier. To avoid encoding the full constant into an instruction,
  1262. // and thus emitting potential call target gadgets at each indirect call
  1263. // site, load a negated constant to a register and compare that to the
  1264. // expected value at the call target.
  1265. const Register AddrReg = MI.getOperand(0).getReg();
  1266. const uint32_t Type = MI.getOperand(1).getImm();
  1267. // The check is immediately before the call. If the call target is in R10,
  1268. // we can clobber R11 for the check instead.
  1269. unsigned TempReg = AddrReg == X86::R10 ? X86::R11D : X86::R10D;
  1270. EmitAndCountInstruction(
  1271. MCInstBuilder(X86::MOV32ri).addReg(TempReg).addImm(-MaskKCFIType(Type)));
  1272. EmitAndCountInstruction(MCInstBuilder(X86::ADD32rm)
  1273. .addReg(X86::NoRegister)
  1274. .addReg(TempReg)
  1275. .addReg(AddrReg)
  1276. .addImm(1)
  1277. .addReg(X86::NoRegister)
  1278. .addImm(-(PrefixNops + 4))
  1279. .addReg(X86::NoRegister));
  1280. MCSymbol *Pass = OutContext.createTempSymbol();
  1281. EmitAndCountInstruction(
  1282. MCInstBuilder(X86::JCC_1)
  1283. .addExpr(MCSymbolRefExpr::create(Pass, OutContext))
  1284. .addImm(X86::COND_E));
  1285. MCSymbol *Trap = OutContext.createTempSymbol();
  1286. OutStreamer->emitLabel(Trap);
  1287. EmitAndCountInstruction(MCInstBuilder(X86::TRAP));
  1288. emitKCFITrapEntry(MF, Trap);
  1289. OutStreamer->emitLabel(Pass);
  1290. }
  1291. void X86AsmPrinter::LowerASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
  1292. // FIXME: Make this work on non-ELF.
  1293. if (!TM.getTargetTriple().isOSBinFormatELF()) {
  1294. report_fatal_error("llvm.asan.check.memaccess only supported on ELF");
  1295. return;
  1296. }
  1297. const auto &Reg = MI.getOperand(0).getReg();
  1298. ASanAccessInfo AccessInfo(MI.getOperand(1).getImm());
  1299. uint64_t ShadowBase;
  1300. int MappingScale;
  1301. bool OrShadowOffset;
  1302. getAddressSanitizerParams(Triple(TM.getTargetTriple()), 64,
  1303. AccessInfo.CompileKernel, &ShadowBase,
  1304. &MappingScale, &OrShadowOffset);
  1305. StringRef Name = AccessInfo.IsWrite ? "store" : "load";
  1306. StringRef Op = OrShadowOffset ? "or" : "add";
  1307. std::string SymName = ("__asan_check_" + Name + "_" + Op + "_" +
  1308. Twine(1ULL << AccessInfo.AccessSizeIndex) + "_" +
  1309. TM.getMCRegisterInfo()->getName(Reg.asMCReg()))
  1310. .str();
  1311. if (OrShadowOffset)
  1312. report_fatal_error(
  1313. "OrShadowOffset is not supported with optimized callbacks");
  1314. EmitAndCountInstruction(
  1315. MCInstBuilder(X86::CALL64pcrel32)
  1316. .addExpr(MCSymbolRefExpr::create(
  1317. OutContext.getOrCreateSymbol(SymName), OutContext)));
  1318. }
  1319. void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
  1320. X86MCInstLower &MCIL) {
  1321. // PATCHABLE_OP minsize, opcode, operands
  1322. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1323. unsigned MinSize = MI.getOperand(0).getImm();
  1324. unsigned Opcode = MI.getOperand(1).getImm();
  1325. // Opcode PATCHABLE_OP is a special case: there is no instruction to wrap,
  1326. // simply emit a nop of size MinSize.
  1327. bool EmptyInst = (Opcode == TargetOpcode::PATCHABLE_OP);
  1328. MCInst MCI;
  1329. MCI.setOpcode(Opcode);
  1330. for (auto &MO : drop_begin(MI.operands(), 2))
  1331. if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
  1332. MCI.addOperand(*MaybeOperand);
  1333. SmallString<256> Code;
  1334. if (!EmptyInst) {
  1335. SmallVector<MCFixup, 4> Fixups;
  1336. raw_svector_ostream VecOS(Code);
  1337. CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
  1338. }
  1339. if (Code.size() < MinSize) {
  1340. if (MinSize == 2 && Subtarget->is32Bit() &&
  1341. Subtarget->isTargetWindowsMSVC() &&
  1342. (Subtarget->getCPU().empty() || Subtarget->getCPU() == "pentium3")) {
  1343. // For compatibility reasons, when targetting MSVC, is is important to
  1344. // generate a 'legacy' NOP in the form of a 8B FF MOV EDI, EDI. Some tools
  1345. // rely specifically on this pattern to be able to patch a function.
  1346. // This is only for 32-bit targets, when using /arch:IA32 or /arch:SSE.
  1347. OutStreamer->emitInstruction(
  1348. MCInstBuilder(X86::MOV32rr_REV).addReg(X86::EDI).addReg(X86::EDI),
  1349. *Subtarget);
  1350. } else if (MinSize == 2 && Opcode == X86::PUSH64r) {
  1351. // This is an optimization that lets us get away without emitting a nop in
  1352. // many cases.
  1353. //
  1354. // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %r9) takes two
  1355. // bytes too, so the check on MinSize is important.
  1356. MCI.setOpcode(X86::PUSH64rmr);
  1357. } else {
  1358. unsigned NopSize = emitNop(*OutStreamer, MinSize, Subtarget);
  1359. assert(NopSize == MinSize && "Could not implement MinSize!");
  1360. (void)NopSize;
  1361. }
  1362. }
  1363. if (!EmptyInst)
  1364. OutStreamer->emitInstruction(MCI, getSubtargetInfo());
  1365. }
  1366. // Lower a stackmap of the form:
  1367. // <id>, <shadowBytes>, ...
  1368. void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
  1369. SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
  1370. auto &Ctx = OutStreamer->getContext();
  1371. MCSymbol *MILabel = Ctx.createTempSymbol();
  1372. OutStreamer->emitLabel(MILabel);
  1373. SM.recordStackMap(*MILabel, MI);
  1374. unsigned NumShadowBytes = MI.getOperand(1).getImm();
  1375. SMShadowTracker.reset(NumShadowBytes);
  1376. }
  1377. // Lower a patchpoint of the form:
  1378. // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
  1379. void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
  1380. X86MCInstLower &MCIL) {
  1381. assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
  1382. SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
  1383. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1384. auto &Ctx = OutStreamer->getContext();
  1385. MCSymbol *MILabel = Ctx.createTempSymbol();
  1386. OutStreamer->emitLabel(MILabel);
  1387. SM.recordPatchPoint(*MILabel, MI);
  1388. PatchPointOpers opers(&MI);
  1389. unsigned ScratchIdx = opers.getNextScratchIdx();
  1390. unsigned EncodedBytes = 0;
  1391. const MachineOperand &CalleeMO = opers.getCallTarget();
  1392. // Check for null target. If target is non-null (i.e. is non-zero or is
  1393. // symbolic) then emit a call.
  1394. if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
  1395. MCOperand CalleeMCOp;
  1396. switch (CalleeMO.getType()) {
  1397. default:
  1398. /// FIXME: Add a verifier check for bad callee types.
  1399. llvm_unreachable("Unrecognized callee operand type.");
  1400. case MachineOperand::MO_Immediate:
  1401. if (CalleeMO.getImm())
  1402. CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
  1403. break;
  1404. case MachineOperand::MO_ExternalSymbol:
  1405. case MachineOperand::MO_GlobalAddress:
  1406. CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
  1407. MCIL.GetSymbolFromOperand(CalleeMO));
  1408. break;
  1409. }
  1410. // Emit MOV to materialize the target address and the CALL to target.
  1411. // This is encoded with 12-13 bytes, depending on which register is used.
  1412. Register ScratchReg = MI.getOperand(ScratchIdx).getReg();
  1413. if (X86II::isX86_64ExtendedReg(ScratchReg))
  1414. EncodedBytes = 13;
  1415. else
  1416. EncodedBytes = 12;
  1417. EmitAndCountInstruction(
  1418. MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
  1419. // FIXME: Add retpoline support and remove this.
  1420. if (Subtarget->useIndirectThunkCalls())
  1421. report_fatal_error(
  1422. "Lowering patchpoint with thunks not yet implemented.");
  1423. EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
  1424. }
  1425. // Emit padding.
  1426. unsigned NumBytes = opers.getNumPatchBytes();
  1427. assert(NumBytes >= EncodedBytes &&
  1428. "Patchpoint can't request size less than the length of a call.");
  1429. emitX86Nops(*OutStreamer, NumBytes - EncodedBytes, Subtarget);
  1430. }
  1431. void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
  1432. X86MCInstLower &MCIL) {
  1433. assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
  1434. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1435. // We want to emit the following pattern, which follows the x86 calling
  1436. // convention to prepare for the trampoline call to be patched in.
  1437. //
  1438. // .p2align 1, ...
  1439. // .Lxray_event_sled_N:
  1440. // jmp +N // jump across the instrumentation sled
  1441. // ... // set up arguments in register
  1442. // callq __xray_CustomEvent@plt // force dependency to symbol
  1443. // ...
  1444. // <jump here>
  1445. //
  1446. // After patching, it would look something like:
  1447. //
  1448. // nopw (2-byte nop)
  1449. // ...
  1450. // callq __xrayCustomEvent // already lowered
  1451. // ...
  1452. //
  1453. // ---
  1454. // First we emit the label and the jump.
  1455. auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
  1456. OutStreamer->AddComment("# XRay Custom Event Log");
  1457. OutStreamer->emitCodeAlignment(Align(2), &getSubtargetInfo());
  1458. OutStreamer->emitLabel(CurSled);
  1459. // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
  1460. // an operand (computed as an offset from the jmp instruction).
  1461. // FIXME: Find another less hacky way do force the relative jump.
  1462. OutStreamer->emitBinaryData("\xeb\x0f");
  1463. // The default C calling convention will place two arguments into %rcx and
  1464. // %rdx -- so we only work with those.
  1465. const Register DestRegs[] = {X86::RDI, X86::RSI};
  1466. bool UsedMask[] = {false, false};
  1467. // Filled out in loop.
  1468. Register SrcRegs[] = {0, 0};
  1469. // Then we put the operands in the %rdi and %rsi registers. We spill the
  1470. // values in the register before we clobber them, and mark them as used in
  1471. // UsedMask. In case the arguments are already in the correct register, we use
  1472. // emit nops appropriately sized to keep the sled the same size in every
  1473. // situation.
  1474. for (unsigned I = 0; I < MI.getNumOperands(); ++I)
  1475. if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
  1476. assert(Op->isReg() && "Only support arguments in registers");
  1477. SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
  1478. if (SrcRegs[I] != DestRegs[I]) {
  1479. UsedMask[I] = true;
  1480. EmitAndCountInstruction(
  1481. MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
  1482. } else {
  1483. emitX86Nops(*OutStreamer, 4, Subtarget);
  1484. }
  1485. }
  1486. // Now that the register values are stashed, mov arguments into place.
  1487. // FIXME: This doesn't work if one of the later SrcRegs is equal to an
  1488. // earlier DestReg. We will have already overwritten over the register before
  1489. // we can copy from it.
  1490. for (unsigned I = 0; I < MI.getNumOperands(); ++I)
  1491. if (SrcRegs[I] != DestRegs[I])
  1492. EmitAndCountInstruction(
  1493. MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
  1494. // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
  1495. // name of the trampoline to be implemented by the XRay runtime.
  1496. auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
  1497. MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
  1498. if (isPositionIndependent())
  1499. TOp.setTargetFlags(X86II::MO_PLT);
  1500. // Emit the call instruction.
  1501. EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
  1502. .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
  1503. // Restore caller-saved and used registers.
  1504. for (unsigned I = sizeof UsedMask; I-- > 0;)
  1505. if (UsedMask[I])
  1506. EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
  1507. else
  1508. emitX86Nops(*OutStreamer, 1, Subtarget);
  1509. OutStreamer->AddComment("xray custom event end.");
  1510. // Record the sled version. Version 0 of this sled was spelled differently, so
  1511. // we let the runtime handle the different offsets we're using. Version 2
  1512. // changed the absolute address to a PC-relative address.
  1513. recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 2);
  1514. }
  1515. void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
  1516. X86MCInstLower &MCIL) {
  1517. assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
  1518. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1519. // We want to emit the following pattern, which follows the x86 calling
  1520. // convention to prepare for the trampoline call to be patched in.
  1521. //
  1522. // .p2align 1, ...
  1523. // .Lxray_event_sled_N:
  1524. // jmp +N // jump across the instrumentation sled
  1525. // ... // set up arguments in register
  1526. // callq __xray_TypedEvent@plt // force dependency to symbol
  1527. // ...
  1528. // <jump here>
  1529. //
  1530. // After patching, it would look something like:
  1531. //
  1532. // nopw (2-byte nop)
  1533. // ...
  1534. // callq __xrayTypedEvent // already lowered
  1535. // ...
  1536. //
  1537. // ---
  1538. // First we emit the label and the jump.
  1539. auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
  1540. OutStreamer->AddComment("# XRay Typed Event Log");
  1541. OutStreamer->emitCodeAlignment(Align(2), &getSubtargetInfo());
  1542. OutStreamer->emitLabel(CurSled);
  1543. // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
  1544. // an operand (computed as an offset from the jmp instruction).
  1545. // FIXME: Find another less hacky way do force the relative jump.
  1546. OutStreamer->emitBinaryData("\xeb\x14");
  1547. // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
  1548. // so we'll work with those. Or we may be called via SystemV, in which case
  1549. // we don't have to do any translation.
  1550. const Register DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
  1551. bool UsedMask[] = {false, false, false};
  1552. // Will fill out src regs in the loop.
  1553. Register SrcRegs[] = {0, 0, 0};
  1554. // Then we put the operands in the SystemV registers. We spill the values in
  1555. // the registers before we clobber them, and mark them as used in UsedMask.
  1556. // In case the arguments are already in the correct register, we emit nops
  1557. // appropriately sized to keep the sled the same size in every situation.
  1558. for (unsigned I = 0; I < MI.getNumOperands(); ++I)
  1559. if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
  1560. // TODO: Is register only support adequate?
  1561. assert(Op->isReg() && "Only supports arguments in registers");
  1562. SrcRegs[I] = getX86SubSuperRegister(Op->getReg(), 64);
  1563. if (SrcRegs[I] != DestRegs[I]) {
  1564. UsedMask[I] = true;
  1565. EmitAndCountInstruction(
  1566. MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
  1567. } else {
  1568. emitX86Nops(*OutStreamer, 4, Subtarget);
  1569. }
  1570. }
  1571. // In the above loop we only stash all of the destination registers or emit
  1572. // nops if the arguments are already in the right place. Doing the actually
  1573. // moving is postponed until after all the registers are stashed so nothing
  1574. // is clobbers. We've already added nops to account for the size of mov and
  1575. // push if the register is in the right place, so we only have to worry about
  1576. // emitting movs.
  1577. // FIXME: This doesn't work if one of the later SrcRegs is equal to an
  1578. // earlier DestReg. We will have already overwritten over the register before
  1579. // we can copy from it.
  1580. for (unsigned I = 0; I < MI.getNumOperands(); ++I)
  1581. if (UsedMask[I])
  1582. EmitAndCountInstruction(
  1583. MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
  1584. // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
  1585. // name of the trampoline to be implemented by the XRay runtime.
  1586. auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
  1587. MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
  1588. if (isPositionIndependent())
  1589. TOp.setTargetFlags(X86II::MO_PLT);
  1590. // Emit the call instruction.
  1591. EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
  1592. .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
  1593. // Restore caller-saved and used registers.
  1594. for (unsigned I = sizeof UsedMask; I-- > 0;)
  1595. if (UsedMask[I])
  1596. EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
  1597. else
  1598. emitX86Nops(*OutStreamer, 1, Subtarget);
  1599. OutStreamer->AddComment("xray typed event end.");
  1600. // Record the sled version.
  1601. recordSled(CurSled, MI, SledKind::TYPED_EVENT, 2);
  1602. }
  1603. void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
  1604. X86MCInstLower &MCIL) {
  1605. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1606. const Function &F = MF->getFunction();
  1607. if (F.hasFnAttribute("patchable-function-entry")) {
  1608. unsigned Num;
  1609. if (F.getFnAttribute("patchable-function-entry")
  1610. .getValueAsString()
  1611. .getAsInteger(10, Num))
  1612. return;
  1613. emitX86Nops(*OutStreamer, Num, Subtarget);
  1614. return;
  1615. }
  1616. // We want to emit the following pattern:
  1617. //
  1618. // .p2align 1, ...
  1619. // .Lxray_sled_N:
  1620. // jmp .tmpN
  1621. // # 9 bytes worth of noops
  1622. //
  1623. // We need the 9 bytes because at runtime, we'd be patching over the full 11
  1624. // bytes with the following pattern:
  1625. //
  1626. // mov %r10, <function id, 32-bit> // 6 bytes
  1627. // call <relative offset, 32-bits> // 5 bytes
  1628. //
  1629. auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
  1630. OutStreamer->emitCodeAlignment(Align(2), &getSubtargetInfo());
  1631. OutStreamer->emitLabel(CurSled);
  1632. // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
  1633. // an operand (computed as an offset from the jmp instruction).
  1634. // FIXME: Find another less hacky way do force the relative jump.
  1635. OutStreamer->emitBytes("\xeb\x09");
  1636. emitX86Nops(*OutStreamer, 9, Subtarget);
  1637. recordSled(CurSled, MI, SledKind::FUNCTION_ENTER, 2);
  1638. }
  1639. void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
  1640. X86MCInstLower &MCIL) {
  1641. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1642. // Since PATCHABLE_RET takes the opcode of the return statement as an
  1643. // argument, we use that to emit the correct form of the RET that we want.
  1644. // i.e. when we see this:
  1645. //
  1646. // PATCHABLE_RET X86::RET ...
  1647. //
  1648. // We should emit the RET followed by sleds.
  1649. //
  1650. // .p2align 1, ...
  1651. // .Lxray_sled_N:
  1652. // ret # or equivalent instruction
  1653. // # 10 bytes worth of noops
  1654. //
  1655. // This just makes sure that the alignment for the next instruction is 2.
  1656. auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
  1657. OutStreamer->emitCodeAlignment(Align(2), &getSubtargetInfo());
  1658. OutStreamer->emitLabel(CurSled);
  1659. unsigned OpCode = MI.getOperand(0).getImm();
  1660. MCInst Ret;
  1661. Ret.setOpcode(OpCode);
  1662. for (auto &MO : drop_begin(MI.operands()))
  1663. if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
  1664. Ret.addOperand(*MaybeOperand);
  1665. OutStreamer->emitInstruction(Ret, getSubtargetInfo());
  1666. emitX86Nops(*OutStreamer, 10, Subtarget);
  1667. recordSled(CurSled, MI, SledKind::FUNCTION_EXIT, 2);
  1668. }
  1669. void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
  1670. X86MCInstLower &MCIL) {
  1671. NoAutoPaddingScope NoPadScope(*OutStreamer);
  1672. // Like PATCHABLE_RET, we have the actual instruction in the operands to this
  1673. // instruction so we lower that particular instruction and its operands.
  1674. // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
  1675. // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
  1676. // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
  1677. // tail call much like how we have it in PATCHABLE_RET.
  1678. auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
  1679. OutStreamer->emitCodeAlignment(Align(2), &getSubtargetInfo());
  1680. OutStreamer->emitLabel(CurSled);
  1681. auto Target = OutContext.createTempSymbol();
  1682. // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
  1683. // an operand (computed as an offset from the jmp instruction).
  1684. // FIXME: Find another less hacky way do force the relative jump.
  1685. OutStreamer->emitBytes("\xeb\x09");
  1686. emitX86Nops(*OutStreamer, 9, Subtarget);
  1687. OutStreamer->emitLabel(Target);
  1688. recordSled(CurSled, MI, SledKind::TAIL_CALL, 2);
  1689. unsigned OpCode = MI.getOperand(0).getImm();
  1690. OpCode = convertTailJumpOpcode(OpCode);
  1691. MCInst TC;
  1692. TC.setOpcode(OpCode);
  1693. // Before emitting the instruction, add a comment to indicate that this is
  1694. // indeed a tail call.
  1695. OutStreamer->AddComment("TAILCALL");
  1696. for (auto &MO : drop_begin(MI.operands()))
  1697. if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
  1698. TC.addOperand(*MaybeOperand);
  1699. OutStreamer->emitInstruction(TC, getSubtargetInfo());
  1700. }
  1701. // Returns instruction preceding MBBI in MachineFunction.
  1702. // If MBBI is the first instruction of the first basic block, returns null.
  1703. static MachineBasicBlock::const_iterator
  1704. PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
  1705. const MachineBasicBlock *MBB = MBBI->getParent();
  1706. while (MBBI == MBB->begin()) {
  1707. if (MBB == &MBB->getParent()->front())
  1708. return MachineBasicBlock::const_iterator();
  1709. MBB = MBB->getPrevNode();
  1710. MBBI = MBB->end();
  1711. }
  1712. --MBBI;
  1713. return MBBI;
  1714. }
  1715. static const Constant *getConstantFromPool(const MachineInstr &MI,
  1716. const MachineOperand &Op) {
  1717. if (!Op.isCPI() || Op.getOffset() != 0)
  1718. return nullptr;
  1719. ArrayRef<MachineConstantPoolEntry> Constants =
  1720. MI.getParent()->getParent()->getConstantPool()->getConstants();
  1721. const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
  1722. // Bail if this is a machine constant pool entry, we won't be able to dig out
  1723. // anything useful.
  1724. if (ConstantEntry.isMachineConstantPoolEntry())
  1725. return nullptr;
  1726. return ConstantEntry.Val.ConstVal;
  1727. }
  1728. static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
  1729. unsigned SrcOp2Idx, ArrayRef<int> Mask) {
  1730. std::string Comment;
  1731. // Compute the name for a register. This is really goofy because we have
  1732. // multiple instruction printers that could (in theory) use different
  1733. // names. Fortunately most people use the ATT style (outside of Windows)
  1734. // and they actually agree on register naming here. Ultimately, this is
  1735. // a comment, and so its OK if it isn't perfect.
  1736. auto GetRegisterName = [](MCRegister Reg) -> StringRef {
  1737. return X86ATTInstPrinter::getRegisterName(Reg);
  1738. };
  1739. const MachineOperand &DstOp = MI->getOperand(0);
  1740. const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
  1741. const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
  1742. StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
  1743. StringRef Src1Name =
  1744. SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
  1745. StringRef Src2Name =
  1746. SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
  1747. // One source operand, fix the mask to print all elements in one span.
  1748. SmallVector<int, 8> ShuffleMask(Mask);
  1749. if (Src1Name == Src2Name)
  1750. for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
  1751. if (ShuffleMask[i] >= e)
  1752. ShuffleMask[i] -= e;
  1753. raw_string_ostream CS(Comment);
  1754. CS << DstName;
  1755. // Handle AVX512 MASK/MASXZ write mask comments.
  1756. // MASK: zmmX {%kY}
  1757. // MASKZ: zmmX {%kY} {z}
  1758. if (SrcOp1Idx > 1) {
  1759. assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
  1760. const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
  1761. if (WriteMaskOp.isReg()) {
  1762. CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
  1763. if (SrcOp1Idx == 2) {
  1764. CS << " {z}";
  1765. }
  1766. }
  1767. }
  1768. CS << " = ";
  1769. for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
  1770. if (i != 0)
  1771. CS << ",";
  1772. if (ShuffleMask[i] == SM_SentinelZero) {
  1773. CS << "zero";
  1774. continue;
  1775. }
  1776. // Otherwise, it must come from src1 or src2. Print the span of elements
  1777. // that comes from this src.
  1778. bool isSrc1 = ShuffleMask[i] < (int)e;
  1779. CS << (isSrc1 ? Src1Name : Src2Name) << '[';
  1780. bool IsFirst = true;
  1781. while (i != e && ShuffleMask[i] != SM_SentinelZero &&
  1782. (ShuffleMask[i] < (int)e) == isSrc1) {
  1783. if (!IsFirst)
  1784. CS << ',';
  1785. else
  1786. IsFirst = false;
  1787. if (ShuffleMask[i] == SM_SentinelUndef)
  1788. CS << "u";
  1789. else
  1790. CS << ShuffleMask[i] % (int)e;
  1791. ++i;
  1792. }
  1793. CS << ']';
  1794. --i; // For loop increments element #.
  1795. }
  1796. CS.flush();
  1797. return Comment;
  1798. }
  1799. static void printConstant(const APInt &Val, raw_ostream &CS) {
  1800. if (Val.getBitWidth() <= 64) {
  1801. CS << Val.getZExtValue();
  1802. } else {
  1803. // print multi-word constant as (w0,w1)
  1804. CS << "(";
  1805. for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
  1806. if (i > 0)
  1807. CS << ",";
  1808. CS << Val.getRawData()[i];
  1809. }
  1810. CS << ")";
  1811. }
  1812. }
  1813. static void printConstant(const APFloat &Flt, raw_ostream &CS) {
  1814. SmallString<32> Str;
  1815. // Force scientific notation to distinquish from integers.
  1816. Flt.toString(Str, 0, 0);
  1817. CS << Str;
  1818. }
  1819. static void printConstant(const Constant *COp, raw_ostream &CS) {
  1820. if (isa<UndefValue>(COp)) {
  1821. CS << "u";
  1822. } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
  1823. printConstant(CI->getValue(), CS);
  1824. } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
  1825. printConstant(CF->getValueAPF(), CS);
  1826. } else {
  1827. CS << "?";
  1828. }
  1829. }
  1830. void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
  1831. assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
  1832. assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
  1833. // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
  1834. if (EmitFPOData) {
  1835. X86TargetStreamer *XTS =
  1836. static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
  1837. switch (MI->getOpcode()) {
  1838. case X86::SEH_PushReg:
  1839. XTS->emitFPOPushReg(MI->getOperand(0).getImm());
  1840. break;
  1841. case X86::SEH_StackAlloc:
  1842. XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
  1843. break;
  1844. case X86::SEH_StackAlign:
  1845. XTS->emitFPOStackAlign(MI->getOperand(0).getImm());
  1846. break;
  1847. case X86::SEH_SetFrame:
  1848. assert(MI->getOperand(1).getImm() == 0 &&
  1849. ".cv_fpo_setframe takes no offset");
  1850. XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
  1851. break;
  1852. case X86::SEH_EndPrologue:
  1853. XTS->emitFPOEndPrologue();
  1854. break;
  1855. case X86::SEH_SaveReg:
  1856. case X86::SEH_SaveXMM:
  1857. case X86::SEH_PushFrame:
  1858. llvm_unreachable("SEH_ directive incompatible with FPO");
  1859. break;
  1860. default:
  1861. llvm_unreachable("expected SEH_ instruction");
  1862. }
  1863. return;
  1864. }
  1865. // Otherwise, use the .seh_ directives for all other Windows platforms.
  1866. switch (MI->getOpcode()) {
  1867. case X86::SEH_PushReg:
  1868. OutStreamer->emitWinCFIPushReg(MI->getOperand(0).getImm());
  1869. break;
  1870. case X86::SEH_SaveReg:
  1871. OutStreamer->emitWinCFISaveReg(MI->getOperand(0).getImm(),
  1872. MI->getOperand(1).getImm());
  1873. break;
  1874. case X86::SEH_SaveXMM:
  1875. OutStreamer->emitWinCFISaveXMM(MI->getOperand(0).getImm(),
  1876. MI->getOperand(1).getImm());
  1877. break;
  1878. case X86::SEH_StackAlloc:
  1879. OutStreamer->emitWinCFIAllocStack(MI->getOperand(0).getImm());
  1880. break;
  1881. case X86::SEH_SetFrame:
  1882. OutStreamer->emitWinCFISetFrame(MI->getOperand(0).getImm(),
  1883. MI->getOperand(1).getImm());
  1884. break;
  1885. case X86::SEH_PushFrame:
  1886. OutStreamer->emitWinCFIPushFrame(MI->getOperand(0).getImm());
  1887. break;
  1888. case X86::SEH_EndPrologue:
  1889. OutStreamer->emitWinCFIEndProlog();
  1890. break;
  1891. default:
  1892. llvm_unreachable("expected SEH_ instruction");
  1893. }
  1894. }
  1895. static unsigned getRegisterWidth(const MCOperandInfo &Info) {
  1896. if (Info.RegClass == X86::VR128RegClassID ||
  1897. Info.RegClass == X86::VR128XRegClassID)
  1898. return 128;
  1899. if (Info.RegClass == X86::VR256RegClassID ||
  1900. Info.RegClass == X86::VR256XRegClassID)
  1901. return 256;
  1902. if (Info.RegClass == X86::VR512RegClassID)
  1903. return 512;
  1904. llvm_unreachable("Unknown register class!");
  1905. }
  1906. static void addConstantComments(const MachineInstr *MI,
  1907. MCStreamer &OutStreamer) {
  1908. switch (MI->getOpcode()) {
  1909. // Lower PSHUFB and VPERMILP normally but add a comment if we can find
  1910. // a constant shuffle mask. We won't be able to do this at the MC layer
  1911. // because the mask isn't an immediate.
  1912. case X86::PSHUFBrm:
  1913. case X86::VPSHUFBrm:
  1914. case X86::VPSHUFBYrm:
  1915. case X86::VPSHUFBZ128rm:
  1916. case X86::VPSHUFBZ128rmk:
  1917. case X86::VPSHUFBZ128rmkz:
  1918. case X86::VPSHUFBZ256rm:
  1919. case X86::VPSHUFBZ256rmk:
  1920. case X86::VPSHUFBZ256rmkz:
  1921. case X86::VPSHUFBZrm:
  1922. case X86::VPSHUFBZrmk:
  1923. case X86::VPSHUFBZrmkz: {
  1924. unsigned SrcIdx = 1;
  1925. if (X86II::isKMasked(MI->getDesc().TSFlags)) {
  1926. // Skip mask operand.
  1927. ++SrcIdx;
  1928. if (X86II::isKMergeMasked(MI->getDesc().TSFlags)) {
  1929. // Skip passthru operand.
  1930. ++SrcIdx;
  1931. }
  1932. }
  1933. unsigned MaskIdx = SrcIdx + 1 + X86::AddrDisp;
  1934. assert(MI->getNumOperands() >= (SrcIdx + 1 + X86::AddrNumOperands) &&
  1935. "Unexpected number of operands!");
  1936. const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
  1937. if (auto *C = getConstantFromPool(*MI, MaskOp)) {
  1938. unsigned Width = getRegisterWidth(MI->getDesc().operands()[0]);
  1939. SmallVector<int, 64> Mask;
  1940. DecodePSHUFBMask(C, Width, Mask);
  1941. if (!Mask.empty())
  1942. OutStreamer.AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
  1943. }
  1944. break;
  1945. }
  1946. case X86::VPERMILPSrm:
  1947. case X86::VPERMILPSYrm:
  1948. case X86::VPERMILPSZ128rm:
  1949. case X86::VPERMILPSZ128rmk:
  1950. case X86::VPERMILPSZ128rmkz:
  1951. case X86::VPERMILPSZ256rm:
  1952. case X86::VPERMILPSZ256rmk:
  1953. case X86::VPERMILPSZ256rmkz:
  1954. case X86::VPERMILPSZrm:
  1955. case X86::VPERMILPSZrmk:
  1956. case X86::VPERMILPSZrmkz:
  1957. case X86::VPERMILPDrm:
  1958. case X86::VPERMILPDYrm:
  1959. case X86::VPERMILPDZ128rm:
  1960. case X86::VPERMILPDZ128rmk:
  1961. case X86::VPERMILPDZ128rmkz:
  1962. case X86::VPERMILPDZ256rm:
  1963. case X86::VPERMILPDZ256rmk:
  1964. case X86::VPERMILPDZ256rmkz:
  1965. case X86::VPERMILPDZrm:
  1966. case X86::VPERMILPDZrmk:
  1967. case X86::VPERMILPDZrmkz: {
  1968. unsigned ElSize;
  1969. switch (MI->getOpcode()) {
  1970. default: llvm_unreachable("Invalid opcode");
  1971. case X86::VPERMILPSrm:
  1972. case X86::VPERMILPSYrm:
  1973. case X86::VPERMILPSZ128rm:
  1974. case X86::VPERMILPSZ256rm:
  1975. case X86::VPERMILPSZrm:
  1976. case X86::VPERMILPSZ128rmkz:
  1977. case X86::VPERMILPSZ256rmkz:
  1978. case X86::VPERMILPSZrmkz:
  1979. case X86::VPERMILPSZ128rmk:
  1980. case X86::VPERMILPSZ256rmk:
  1981. case X86::VPERMILPSZrmk:
  1982. ElSize = 32;
  1983. break;
  1984. case X86::VPERMILPDrm:
  1985. case X86::VPERMILPDYrm:
  1986. case X86::VPERMILPDZ128rm:
  1987. case X86::VPERMILPDZ256rm:
  1988. case X86::VPERMILPDZrm:
  1989. case X86::VPERMILPDZ128rmkz:
  1990. case X86::VPERMILPDZ256rmkz:
  1991. case X86::VPERMILPDZrmkz:
  1992. case X86::VPERMILPDZ128rmk:
  1993. case X86::VPERMILPDZ256rmk:
  1994. case X86::VPERMILPDZrmk:
  1995. ElSize = 64;
  1996. break;
  1997. }
  1998. unsigned SrcIdx = 1;
  1999. if (X86II::isKMasked(MI->getDesc().TSFlags)) {
  2000. // Skip mask operand.
  2001. ++SrcIdx;
  2002. if (X86II::isKMergeMasked(MI->getDesc().TSFlags)) {
  2003. // Skip passthru operand.
  2004. ++SrcIdx;
  2005. }
  2006. }
  2007. unsigned MaskIdx = SrcIdx + 1 + X86::AddrDisp;
  2008. assert(MI->getNumOperands() >= (SrcIdx + 1 + X86::AddrNumOperands) &&
  2009. "Unexpected number of operands!");
  2010. const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
  2011. if (auto *C = getConstantFromPool(*MI, MaskOp)) {
  2012. unsigned Width = getRegisterWidth(MI->getDesc().operands()[0]);
  2013. SmallVector<int, 16> Mask;
  2014. DecodeVPERMILPMask(C, ElSize, Width, Mask);
  2015. if (!Mask.empty())
  2016. OutStreamer.AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask));
  2017. }
  2018. break;
  2019. }
  2020. case X86::VPERMIL2PDrm:
  2021. case X86::VPERMIL2PSrm:
  2022. case X86::VPERMIL2PDYrm:
  2023. case X86::VPERMIL2PSYrm: {
  2024. assert(MI->getNumOperands() >= (3 + X86::AddrNumOperands + 1) &&
  2025. "Unexpected number of operands!");
  2026. const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
  2027. if (!CtrlOp.isImm())
  2028. break;
  2029. unsigned ElSize;
  2030. switch (MI->getOpcode()) {
  2031. default: llvm_unreachable("Invalid opcode");
  2032. case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
  2033. case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
  2034. }
  2035. const MachineOperand &MaskOp = MI->getOperand(3 + X86::AddrDisp);
  2036. if (auto *C = getConstantFromPool(*MI, MaskOp)) {
  2037. unsigned Width = getRegisterWidth(MI->getDesc().operands()[0]);
  2038. SmallVector<int, 16> Mask;
  2039. DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Width, Mask);
  2040. if (!Mask.empty())
  2041. OutStreamer.AddComment(getShuffleComment(MI, 1, 2, Mask));
  2042. }
  2043. break;
  2044. }
  2045. case X86::VPPERMrrm: {
  2046. assert(MI->getNumOperands() >= (3 + X86::AddrNumOperands) &&
  2047. "Unexpected number of operands!");
  2048. const MachineOperand &MaskOp = MI->getOperand(3 + X86::AddrDisp);
  2049. if (auto *C = getConstantFromPool(*MI, MaskOp)) {
  2050. unsigned Width = getRegisterWidth(MI->getDesc().operands()[0]);
  2051. SmallVector<int, 16> Mask;
  2052. DecodeVPPERMMask(C, Width, Mask);
  2053. if (!Mask.empty())
  2054. OutStreamer.AddComment(getShuffleComment(MI, 1, 2, Mask));
  2055. }
  2056. break;
  2057. }
  2058. case X86::MMX_MOVQ64rm: {
  2059. assert(MI->getNumOperands() == (1 + X86::AddrNumOperands) &&
  2060. "Unexpected number of operands!");
  2061. if (auto *C = getConstantFromPool(*MI, MI->getOperand(1 + X86::AddrDisp))) {
  2062. std::string Comment;
  2063. raw_string_ostream CS(Comment);
  2064. const MachineOperand &DstOp = MI->getOperand(0);
  2065. CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
  2066. if (auto *CF = dyn_cast<ConstantFP>(C)) {
  2067. CS << "0x" << toString(CF->getValueAPF().bitcastToAPInt(), 16, false);
  2068. OutStreamer.AddComment(CS.str());
  2069. }
  2070. }
  2071. break;
  2072. }
  2073. #define MOV_CASE(Prefix, Suffix) \
  2074. case X86::Prefix##MOVAPD##Suffix##rm: \
  2075. case X86::Prefix##MOVAPS##Suffix##rm: \
  2076. case X86::Prefix##MOVUPD##Suffix##rm: \
  2077. case X86::Prefix##MOVUPS##Suffix##rm: \
  2078. case X86::Prefix##MOVDQA##Suffix##rm: \
  2079. case X86::Prefix##MOVDQU##Suffix##rm:
  2080. #define MOV_AVX512_CASE(Suffix) \
  2081. case X86::VMOVDQA64##Suffix##rm: \
  2082. case X86::VMOVDQA32##Suffix##rm: \
  2083. case X86::VMOVDQU64##Suffix##rm: \
  2084. case X86::VMOVDQU32##Suffix##rm: \
  2085. case X86::VMOVDQU16##Suffix##rm: \
  2086. case X86::VMOVDQU8##Suffix##rm: \
  2087. case X86::VMOVAPS##Suffix##rm: \
  2088. case X86::VMOVAPD##Suffix##rm: \
  2089. case X86::VMOVUPS##Suffix##rm: \
  2090. case X86::VMOVUPD##Suffix##rm:
  2091. #define CASE_ALL_MOV_RM() \
  2092. MOV_CASE(, ) /* SSE */ \
  2093. MOV_CASE(V, ) /* AVX-128 */ \
  2094. MOV_CASE(V, Y) /* AVX-256 */ \
  2095. MOV_AVX512_CASE(Z) \
  2096. MOV_AVX512_CASE(Z256) \
  2097. MOV_AVX512_CASE(Z128)
  2098. // For loads from a constant pool to a vector register, print the constant
  2099. // loaded.
  2100. CASE_ALL_MOV_RM()
  2101. case X86::VBROADCASTF128:
  2102. case X86::VBROADCASTI128:
  2103. case X86::VBROADCASTF32X4Z256rm:
  2104. case X86::VBROADCASTF32X4rm:
  2105. case X86::VBROADCASTF32X8rm:
  2106. case X86::VBROADCASTF64X2Z128rm:
  2107. case X86::VBROADCASTF64X2rm:
  2108. case X86::VBROADCASTF64X4rm:
  2109. case X86::VBROADCASTI32X4Z256rm:
  2110. case X86::VBROADCASTI32X4rm:
  2111. case X86::VBROADCASTI32X8rm:
  2112. case X86::VBROADCASTI64X2Z128rm:
  2113. case X86::VBROADCASTI64X2rm:
  2114. case X86::VBROADCASTI64X4rm:
  2115. assert(MI->getNumOperands() >= (1 + X86::AddrNumOperands) &&
  2116. "Unexpected number of operands!");
  2117. if (auto *C = getConstantFromPool(*MI, MI->getOperand(1 + X86::AddrDisp))) {
  2118. int NumLanes = 1;
  2119. // Override NumLanes for the broadcast instructions.
  2120. switch (MI->getOpcode()) {
  2121. case X86::VBROADCASTF128: NumLanes = 2; break;
  2122. case X86::VBROADCASTI128: NumLanes = 2; break;
  2123. case X86::VBROADCASTF32X4Z256rm: NumLanes = 2; break;
  2124. case X86::VBROADCASTF32X4rm: NumLanes = 4; break;
  2125. case X86::VBROADCASTF32X8rm: NumLanes = 2; break;
  2126. case X86::VBROADCASTF64X2Z128rm: NumLanes = 2; break;
  2127. case X86::VBROADCASTF64X2rm: NumLanes = 4; break;
  2128. case X86::VBROADCASTF64X4rm: NumLanes = 2; break;
  2129. case X86::VBROADCASTI32X4Z256rm: NumLanes = 2; break;
  2130. case X86::VBROADCASTI32X4rm: NumLanes = 4; break;
  2131. case X86::VBROADCASTI32X8rm: NumLanes = 2; break;
  2132. case X86::VBROADCASTI64X2Z128rm: NumLanes = 2; break;
  2133. case X86::VBROADCASTI64X2rm: NumLanes = 4; break;
  2134. case X86::VBROADCASTI64X4rm: NumLanes = 2; break;
  2135. }
  2136. std::string Comment;
  2137. raw_string_ostream CS(Comment);
  2138. const MachineOperand &DstOp = MI->getOperand(0);
  2139. CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
  2140. if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
  2141. CS << "[";
  2142. for (int l = 0; l != NumLanes; ++l) {
  2143. for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements;
  2144. ++i) {
  2145. if (i != 0 || l != 0)
  2146. CS << ",";
  2147. if (CDS->getElementType()->isIntegerTy())
  2148. printConstant(CDS->getElementAsAPInt(i), CS);
  2149. else if (CDS->getElementType()->isHalfTy() ||
  2150. CDS->getElementType()->isFloatTy() ||
  2151. CDS->getElementType()->isDoubleTy())
  2152. printConstant(CDS->getElementAsAPFloat(i), CS);
  2153. else
  2154. CS << "?";
  2155. }
  2156. }
  2157. CS << "]";
  2158. OutStreamer.AddComment(CS.str());
  2159. } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
  2160. CS << "<";
  2161. for (int l = 0; l != NumLanes; ++l) {
  2162. for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands;
  2163. ++i) {
  2164. if (i != 0 || l != 0)
  2165. CS << ",";
  2166. printConstant(CV->getOperand(i), CS);
  2167. }
  2168. }
  2169. CS << ">";
  2170. OutStreamer.AddComment(CS.str());
  2171. }
  2172. }
  2173. break;
  2174. case X86::MOVDDUPrm:
  2175. case X86::VMOVDDUPrm:
  2176. case X86::VMOVDDUPZ128rm:
  2177. case X86::VBROADCASTSSrm:
  2178. case X86::VBROADCASTSSYrm:
  2179. case X86::VBROADCASTSSZ128rm:
  2180. case X86::VBROADCASTSSZ256rm:
  2181. case X86::VBROADCASTSSZrm:
  2182. case X86::VBROADCASTSDYrm:
  2183. case X86::VBROADCASTSDZ256rm:
  2184. case X86::VBROADCASTSDZrm:
  2185. case X86::VPBROADCASTBrm:
  2186. case X86::VPBROADCASTBYrm:
  2187. case X86::VPBROADCASTBZ128rm:
  2188. case X86::VPBROADCASTBZ256rm:
  2189. case X86::VPBROADCASTBZrm:
  2190. case X86::VPBROADCASTDrm:
  2191. case X86::VPBROADCASTDYrm:
  2192. case X86::VPBROADCASTDZ128rm:
  2193. case X86::VPBROADCASTDZ256rm:
  2194. case X86::VPBROADCASTDZrm:
  2195. case X86::VPBROADCASTQrm:
  2196. case X86::VPBROADCASTQYrm:
  2197. case X86::VPBROADCASTQZ128rm:
  2198. case X86::VPBROADCASTQZ256rm:
  2199. case X86::VPBROADCASTQZrm:
  2200. case X86::VPBROADCASTWrm:
  2201. case X86::VPBROADCASTWYrm:
  2202. case X86::VPBROADCASTWZ128rm:
  2203. case X86::VPBROADCASTWZ256rm:
  2204. case X86::VPBROADCASTWZrm:
  2205. assert(MI->getNumOperands() >= (1 + X86::AddrNumOperands) &&
  2206. "Unexpected number of operands!");
  2207. if (auto *C = getConstantFromPool(*MI, MI->getOperand(1 + X86::AddrDisp))) {
  2208. int NumElts;
  2209. switch (MI->getOpcode()) {
  2210. default: llvm_unreachable("Invalid opcode");
  2211. case X86::MOVDDUPrm: NumElts = 2; break;
  2212. case X86::VMOVDDUPrm: NumElts = 2; break;
  2213. case X86::VMOVDDUPZ128rm: NumElts = 2; break;
  2214. case X86::VBROADCASTSSrm: NumElts = 4; break;
  2215. case X86::VBROADCASTSSYrm: NumElts = 8; break;
  2216. case X86::VBROADCASTSSZ128rm: NumElts = 4; break;
  2217. case X86::VBROADCASTSSZ256rm: NumElts = 8; break;
  2218. case X86::VBROADCASTSSZrm: NumElts = 16; break;
  2219. case X86::VBROADCASTSDYrm: NumElts = 4; break;
  2220. case X86::VBROADCASTSDZ256rm: NumElts = 4; break;
  2221. case X86::VBROADCASTSDZrm: NumElts = 8; break;
  2222. case X86::VPBROADCASTBrm: NumElts = 16; break;
  2223. case X86::VPBROADCASTBYrm: NumElts = 32; break;
  2224. case X86::VPBROADCASTBZ128rm: NumElts = 16; break;
  2225. case X86::VPBROADCASTBZ256rm: NumElts = 32; break;
  2226. case X86::VPBROADCASTBZrm: NumElts = 64; break;
  2227. case X86::VPBROADCASTDrm: NumElts = 4; break;
  2228. case X86::VPBROADCASTDYrm: NumElts = 8; break;
  2229. case X86::VPBROADCASTDZ128rm: NumElts = 4; break;
  2230. case X86::VPBROADCASTDZ256rm: NumElts = 8; break;
  2231. case X86::VPBROADCASTDZrm: NumElts = 16; break;
  2232. case X86::VPBROADCASTQrm: NumElts = 2; break;
  2233. case X86::VPBROADCASTQYrm: NumElts = 4; break;
  2234. case X86::VPBROADCASTQZ128rm: NumElts = 2; break;
  2235. case X86::VPBROADCASTQZ256rm: NumElts = 4; break;
  2236. case X86::VPBROADCASTQZrm: NumElts = 8; break;
  2237. case X86::VPBROADCASTWrm: NumElts = 8; break;
  2238. case X86::VPBROADCASTWYrm: NumElts = 16; break;
  2239. case X86::VPBROADCASTWZ128rm: NumElts = 8; break;
  2240. case X86::VPBROADCASTWZ256rm: NumElts = 16; break;
  2241. case X86::VPBROADCASTWZrm: NumElts = 32; break;
  2242. }
  2243. std::string Comment;
  2244. raw_string_ostream CS(Comment);
  2245. const MachineOperand &DstOp = MI->getOperand(0);
  2246. CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
  2247. CS << "[";
  2248. for (int i = 0; i != NumElts; ++i) {
  2249. if (i != 0)
  2250. CS << ",";
  2251. printConstant(C, CS);
  2252. }
  2253. CS << "]";
  2254. OutStreamer.AddComment(CS.str());
  2255. }
  2256. }
  2257. }
  2258. void X86AsmPrinter::emitInstruction(const MachineInstr *MI) {
  2259. // FIXME: Enable feature predicate checks once all the test pass.
  2260. // X86_MC::verifyInstructionPredicates(MI->getOpcode(),
  2261. // Subtarget->getFeatureBits());
  2262. X86MCInstLower MCInstLowering(*MF, *this);
  2263. const X86RegisterInfo *RI =
  2264. MF->getSubtarget<X86Subtarget>().getRegisterInfo();
  2265. if (MI->getOpcode() == X86::OR64rm) {
  2266. for (auto &Opd : MI->operands()) {
  2267. if (Opd.isSymbol() && StringRef(Opd.getSymbolName()) ==
  2268. "swift_async_extendedFramePointerFlags") {
  2269. ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags = true;
  2270. }
  2271. }
  2272. }
  2273. // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
  2274. // are compressed from EVEX encoding to VEX encoding.
  2275. if (TM.Options.MCOptions.ShowMCEncoding) {
  2276. if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_VEX)
  2277. OutStreamer->AddComment("EVEX TO VEX Compression ", false);
  2278. }
  2279. // Add comments for values loaded from constant pool.
  2280. if (OutStreamer->isVerboseAsm())
  2281. addConstantComments(MI, *OutStreamer);
  2282. switch (MI->getOpcode()) {
  2283. case TargetOpcode::DBG_VALUE:
  2284. llvm_unreachable("Should be handled target independently");
  2285. case X86::EH_RETURN:
  2286. case X86::EH_RETURN64: {
  2287. // Lower these as normal, but add some comments.
  2288. Register Reg = MI->getOperand(0).getReg();
  2289. OutStreamer->AddComment(StringRef("eh_return, addr: %") +
  2290. X86ATTInstPrinter::getRegisterName(Reg));
  2291. break;
  2292. }
  2293. case X86::CLEANUPRET: {
  2294. // Lower these as normal, but add some comments.
  2295. OutStreamer->AddComment("CLEANUPRET");
  2296. break;
  2297. }
  2298. case X86::CATCHRET: {
  2299. // Lower these as normal, but add some comments.
  2300. OutStreamer->AddComment("CATCHRET");
  2301. break;
  2302. }
  2303. case X86::ENDBR32:
  2304. case X86::ENDBR64: {
  2305. // CurrentPatchableFunctionEntrySym can be CurrentFnBegin only for
  2306. // -fpatchable-function-entry=N,0. The entry MBB is guaranteed to be
  2307. // non-empty. If MI is the initial ENDBR, place the
  2308. // __patchable_function_entries label after ENDBR.
  2309. if (CurrentPatchableFunctionEntrySym &&
  2310. CurrentPatchableFunctionEntrySym == CurrentFnBegin &&
  2311. MI == &MF->front().front()) {
  2312. MCInst Inst;
  2313. MCInstLowering.Lower(MI, Inst);
  2314. EmitAndCountInstruction(Inst);
  2315. CurrentPatchableFunctionEntrySym = createTempSymbol("patch");
  2316. OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
  2317. return;
  2318. }
  2319. break;
  2320. }
  2321. case X86::TAILJMPd64:
  2322. if (IndCSPrefix && MI->hasRegisterImplicitUseOperand(X86::R11))
  2323. EmitAndCountInstruction(MCInstBuilder(X86::CS_PREFIX));
  2324. [[fallthrough]];
  2325. case X86::TAILJMPr:
  2326. case X86::TAILJMPm:
  2327. case X86::TAILJMPd:
  2328. case X86::TAILJMPd_CC:
  2329. case X86::TAILJMPr64:
  2330. case X86::TAILJMPm64:
  2331. case X86::TAILJMPd64_CC:
  2332. case X86::TAILJMPr64_REX:
  2333. case X86::TAILJMPm64_REX:
  2334. // Lower these as normal, but add some comments.
  2335. OutStreamer->AddComment("TAILCALL");
  2336. break;
  2337. case X86::TLS_addr32:
  2338. case X86::TLS_addr64:
  2339. case X86::TLS_addrX32:
  2340. case X86::TLS_base_addr32:
  2341. case X86::TLS_base_addr64:
  2342. case X86::TLS_base_addrX32:
  2343. return LowerTlsAddr(MCInstLowering, *MI);
  2344. case X86::MOVPC32r: {
  2345. // This is a pseudo op for a two instruction sequence with a label, which
  2346. // looks like:
  2347. // call "L1$pb"
  2348. // "L1$pb":
  2349. // popl %esi
  2350. // Emit the call.
  2351. MCSymbol *PICBase = MF->getPICBaseSymbol();
  2352. // FIXME: We would like an efficient form for this, so we don't have to do a
  2353. // lot of extra uniquing.
  2354. EmitAndCountInstruction(
  2355. MCInstBuilder(X86::CALLpcrel32)
  2356. .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
  2357. const X86FrameLowering *FrameLowering =
  2358. MF->getSubtarget<X86Subtarget>().getFrameLowering();
  2359. bool hasFP = FrameLowering->hasFP(*MF);
  2360. // TODO: This is needed only if we require precise CFA.
  2361. bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
  2362. !OutStreamer->getDwarfFrameInfos().back().End;
  2363. int stackGrowth = -RI->getSlotSize();
  2364. if (HasActiveDwarfFrame && !hasFP) {
  2365. OutStreamer->emitCFIAdjustCfaOffset(-stackGrowth);
  2366. }
  2367. // Emit the label.
  2368. OutStreamer->emitLabel(PICBase);
  2369. // popl $reg
  2370. EmitAndCountInstruction(
  2371. MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
  2372. if (HasActiveDwarfFrame && !hasFP) {
  2373. OutStreamer->emitCFIAdjustCfaOffset(stackGrowth);
  2374. }
  2375. return;
  2376. }
  2377. case X86::ADD32ri: {
  2378. // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
  2379. if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
  2380. break;
  2381. // Okay, we have something like:
  2382. // EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
  2383. // For this, we want to print something like:
  2384. // MYGLOBAL + (. - PICBASE)
  2385. // However, we can't generate a ".", so just emit a new label here and refer
  2386. // to it.
  2387. MCSymbol *DotSym = OutContext.createTempSymbol();
  2388. OutStreamer->emitLabel(DotSym);
  2389. // Now that we have emitted the label, lower the complex operand expression.
  2390. MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
  2391. const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
  2392. const MCExpr *PICBase =
  2393. MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
  2394. DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
  2395. DotExpr = MCBinaryExpr::createAdd(
  2396. MCSymbolRefExpr::create(OpSym, OutContext), DotExpr, OutContext);
  2397. EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
  2398. .addReg(MI->getOperand(0).getReg())
  2399. .addReg(MI->getOperand(1).getReg())
  2400. .addExpr(DotExpr));
  2401. return;
  2402. }
  2403. case TargetOpcode::STATEPOINT:
  2404. return LowerSTATEPOINT(*MI, MCInstLowering);
  2405. case TargetOpcode::FAULTING_OP:
  2406. return LowerFAULTING_OP(*MI, MCInstLowering);
  2407. case TargetOpcode::FENTRY_CALL:
  2408. return LowerFENTRY_CALL(*MI, MCInstLowering);
  2409. case TargetOpcode::PATCHABLE_OP:
  2410. return LowerPATCHABLE_OP(*MI, MCInstLowering);
  2411. case TargetOpcode::STACKMAP:
  2412. return LowerSTACKMAP(*MI);
  2413. case TargetOpcode::PATCHPOINT:
  2414. return LowerPATCHPOINT(*MI, MCInstLowering);
  2415. case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
  2416. return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
  2417. case TargetOpcode::PATCHABLE_RET:
  2418. return LowerPATCHABLE_RET(*MI, MCInstLowering);
  2419. case TargetOpcode::PATCHABLE_TAIL_CALL:
  2420. return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
  2421. case TargetOpcode::PATCHABLE_EVENT_CALL:
  2422. return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
  2423. case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
  2424. return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
  2425. case X86::MORESTACK_RET:
  2426. EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
  2427. return;
  2428. case X86::KCFI_CHECK:
  2429. return LowerKCFI_CHECK(*MI);
  2430. case X86::ASAN_CHECK_MEMACCESS:
  2431. return LowerASAN_CHECK_MEMACCESS(*MI);
  2432. case X86::MORESTACK_RET_RESTORE_R10:
  2433. // Return, then restore R10.
  2434. EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
  2435. EmitAndCountInstruction(
  2436. MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
  2437. return;
  2438. case X86::SEH_PushReg:
  2439. case X86::SEH_SaveReg:
  2440. case X86::SEH_SaveXMM:
  2441. case X86::SEH_StackAlloc:
  2442. case X86::SEH_StackAlign:
  2443. case X86::SEH_SetFrame:
  2444. case X86::SEH_PushFrame:
  2445. case X86::SEH_EndPrologue:
  2446. EmitSEHInstruction(MI);
  2447. return;
  2448. case X86::SEH_Epilogue: {
  2449. assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
  2450. MachineBasicBlock::const_iterator MBBI(MI);
  2451. // Check if preceded by a call and emit nop if so.
  2452. for (MBBI = PrevCrossBBInst(MBBI);
  2453. MBBI != MachineBasicBlock::const_iterator();
  2454. MBBI = PrevCrossBBInst(MBBI)) {
  2455. // Conservatively assume that pseudo instructions don't emit code and keep
  2456. // looking for a call. We may emit an unnecessary nop in some cases.
  2457. if (!MBBI->isPseudo()) {
  2458. if (MBBI->isCall())
  2459. EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
  2460. break;
  2461. }
  2462. }
  2463. return;
  2464. }
  2465. case X86::UBSAN_UD1:
  2466. EmitAndCountInstruction(MCInstBuilder(X86::UD1Lm)
  2467. .addReg(X86::EAX)
  2468. .addReg(X86::EAX)
  2469. .addImm(1)
  2470. .addReg(X86::NoRegister)
  2471. .addImm(MI->getOperand(0).getImm())
  2472. .addReg(X86::NoRegister));
  2473. return;
  2474. case X86::CALL64pcrel32:
  2475. if (IndCSPrefix && MI->hasRegisterImplicitUseOperand(X86::R11))
  2476. EmitAndCountInstruction(MCInstBuilder(X86::CS_PREFIX));
  2477. break;
  2478. }
  2479. MCInst TmpInst;
  2480. MCInstLowering.Lower(MI, TmpInst);
  2481. // Stackmap shadows cannot include branch targets, so we can count the bytes
  2482. // in a call towards the shadow, but must ensure that the no thread returns
  2483. // in to the stackmap shadow. The only way to achieve this is if the call
  2484. // is at the end of the shadow.
  2485. if (MI->isCall()) {
  2486. // Count then size of the call towards the shadow
  2487. SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
  2488. // Then flush the shadow so that we fill with nops before the call, not
  2489. // after it.
  2490. SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
  2491. // Then emit the call
  2492. OutStreamer->emitInstruction(TmpInst, getSubtargetInfo());
  2493. return;
  2494. }
  2495. EmitAndCountInstruction(TmpInst);
  2496. }