X86MCInstLower.cpp 99 KB

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