1 //===-- X86AsmBackend.cpp - X86 Assembler Backend -------------------------===//
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 #include "MCTargetDesc/X86BaseInfo.h"
10 #include "MCTargetDesc/X86FixupKinds.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/BinaryFormat/ELF.h"
13 #include "llvm/BinaryFormat/MachO.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCELFObjectWriter.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCMachObjectWriter.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 
37 using namespace llvm;
38 
39 namespace {
40 /// A wrapper for holding a mask of the values from X86::AlignBranchBoundaryKind
41 class X86AlignBranchKind {
42 private:
43   uint8_t AlignBranchKind = 0;
44 
45 public:
46   void operator=(const std::string &Val) {
47     if (Val.empty())
48       return;
49     SmallVector<StringRef, 6> BranchTypes;
50     StringRef(Val).split(BranchTypes, '+', -1, false);
51     for (auto BranchType : BranchTypes) {
52       if (BranchType == "fused")
53         addKind(X86::AlignBranchFused);
54       else if (BranchType == "jcc")
55         addKind(X86::AlignBranchJcc);
56       else if (BranchType == "jmp")
57         addKind(X86::AlignBranchJmp);
58       else if (BranchType == "call")
59         addKind(X86::AlignBranchCall);
60       else if (BranchType == "ret")
61         addKind(X86::AlignBranchRet);
62       else if (BranchType == "indirect")
63         addKind(X86::AlignBranchIndirect);
64       else {
65         report_fatal_error(
66             "'-x86-align-branch 'The branches's type is combination of jcc, "
67             "fused, jmp, call, ret, indirect.(plus separated)",
68             false);
69       }
70     }
71   }
72 
73   operator uint8_t() const { return AlignBranchKind; }
74   void addKind(X86::AlignBranchBoundaryKind Value) { AlignBranchKind |= Value; }
75 };
76 
77 X86AlignBranchKind X86AlignBranchKindLoc;
78 
79 cl::opt<unsigned> X86AlignBranchBoundary(
80     "x86-align-branch-boundary", cl::init(0),
81     cl::desc(
82         "Control how the assembler should align branches with NOP. If the "
83         "boundary's size is not 0, it should be a power of 2 and no less "
84         "than 32. Branches will be aligned to prevent from being across or "
85         "against the boundary of specified size. The default value 0 does not "
86         "align branches."));
87 
88 cl::opt<X86AlignBranchKind, true, cl::parser<std::string>> X86AlignBranch(
89     "x86-align-branch",
90     cl::desc(
91         "Specify types of branches to align (plus separated list of types):"
92              "\njcc      indicates conditional jumps"
93              "\nfused    indicates fused conditional jumps"
94              "\njmp      indicates direct unconditional jumps"
95              "\ncall     indicates direct and indirect calls"
96              "\nret      indicates rets"
97              "\nindirect indicates indirect unconditional jumps"),
98     cl::location(X86AlignBranchKindLoc));
99 
100 cl::opt<bool> X86AlignBranchWithin32BBoundaries(
101     "x86-branches-within-32B-boundaries", cl::init(false),
102     cl::desc(
103         "Align selected instructions to mitigate negative performance impact "
104         "of Intel's micro code update for errata skx102.  May break "
105         "assumptions about labels corresponding to particular instructions, "
106         "and should be used with caution."));
107 
108 cl::opt<unsigned> X86PadMaxPrefixSize(
109     "x86-pad-max-prefix-size", cl::init(0),
110     cl::desc("Maximum number of prefixes to use for padding"));
111 
112 cl::opt<bool> X86PadForAlign(
113     "x86-pad-for-align", cl::init(true), cl::Hidden,
114     cl::desc("Pad previous instructions to implement align directives"));
115 
116 cl::opt<bool> X86PadForBranchAlign(
117     "x86-pad-for-branch-align", cl::init(true), cl::Hidden,
118     cl::desc("Pad previous instructions to implement branch alignment"));
119 
120 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
121 public:
122   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
123                      bool HasRelocationAddend, bool foobar)
124     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
125 };
126 
127 class X86AsmBackend : public MCAsmBackend {
128   const MCSubtargetInfo &STI;
129   std::unique_ptr<const MCInstrInfo> MCII;
130   X86AlignBranchKind AlignBranchType;
131   Align AlignBoundary;
132 
133   uint8_t determinePaddingPrefix(const MCInst &Inst) const;
134 
135   bool isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const;
136 
137   bool needAlign(MCObjectStreamer &OS) const;
138   bool needAlignInst(const MCInst &Inst) const;
139   bool allowAutoPaddingForInst(const MCInst &Inst, MCObjectStreamer &OS) const;
140   MCInst PrevInst;
141   MCBoundaryAlignFragment *PendingBoundaryAlign = nullptr;
142   std::pair<MCFragment *, size_t> PrevInstPosition;
143   bool AllowAutoPaddingForInst;
144 
145 public:
146   X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
147       : MCAsmBackend(support::little), STI(STI),
148         MCII(T.createMCInstrInfo()) {
149     if (X86AlignBranchWithin32BBoundaries) {
150       // At the moment, this defaults to aligning fused branches, unconditional
151       // jumps, and (unfused) conditional jumps with nops.  Both the
152       // instructions aligned and the alignment method (nop vs prefix) may
153       // change in the future.
154       AlignBoundary = assumeAligned(32);;
155       AlignBranchType.addKind(X86::AlignBranchFused);
156       AlignBranchType.addKind(X86::AlignBranchJcc);
157       AlignBranchType.addKind(X86::AlignBranchJmp);
158     }
159     // Allow overriding defaults set by master flag
160     if (X86AlignBranchBoundary.getNumOccurrences())
161       AlignBoundary = assumeAligned(X86AlignBranchBoundary);
162     if (X86AlignBranch.getNumOccurrences())
163       AlignBranchType = X86AlignBranchKindLoc;
164   }
165 
166   bool allowAutoPadding() const override;
167   void emitInstructionBegin(MCObjectStreamer &OS, const MCInst &Inst) override;
168   void emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst) override;
169 
170   unsigned getNumFixupKinds() const override {
171     return X86::NumTargetFixupKinds;
172   }
173 
174   Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
175 
176   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override;
177 
178   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
179                              const MCValue &Target) override;
180 
181   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
182                   const MCValue &Target, MutableArrayRef<char> Data,
183                   uint64_t Value, bool IsResolved,
184                   const MCSubtargetInfo *STI) const override;
185 
186   bool mayNeedRelaxation(const MCInst &Inst,
187                          const MCSubtargetInfo &STI) const override;
188 
189   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
190                             const MCRelaxableFragment *DF,
191                             const MCAsmLayout &Layout) const override;
192 
193   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
194                         MCInst &Res) const override;
195 
196   bool padInstructionViaRelaxation(MCRelaxableFragment &RF,
197                                    MCCodeEmitter &Emitter,
198                                    unsigned &RemainingSize) const;
199 
200   bool padInstructionViaPrefix(MCRelaxableFragment &RF, MCCodeEmitter &Emitter,
201                                unsigned &RemainingSize) const;
202 
203   bool padInstructionEncoding(MCRelaxableFragment &RF, MCCodeEmitter &Emitter,
204                               unsigned &RemainingSize) const;
205 
206   void finishLayout(MCAssembler const &Asm, MCAsmLayout &Layout) const override;
207 
208   bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
209 };
210 } // end anonymous namespace
211 
212 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool Is16BitMode) {
213   unsigned Op = Inst.getOpcode();
214   switch (Op) {
215   default:
216     return Op;
217   case X86::JCC_1:
218     return (Is16BitMode) ? X86::JCC_2 : X86::JCC_4;
219   case X86::JMP_1:
220     return (Is16BitMode) ? X86::JMP_2 : X86::JMP_4;
221   }
222 }
223 
224 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
225   unsigned Op = Inst.getOpcode();
226   switch (Op) {
227   default:
228     return Op;
229 
230     // IMUL
231   case X86::IMUL16rri8: return X86::IMUL16rri;
232   case X86::IMUL16rmi8: return X86::IMUL16rmi;
233   case X86::IMUL32rri8: return X86::IMUL32rri;
234   case X86::IMUL32rmi8: return X86::IMUL32rmi;
235   case X86::IMUL64rri8: return X86::IMUL64rri32;
236   case X86::IMUL64rmi8: return X86::IMUL64rmi32;
237 
238     // AND
239   case X86::AND16ri8: return X86::AND16ri;
240   case X86::AND16mi8: return X86::AND16mi;
241   case X86::AND32ri8: return X86::AND32ri;
242   case X86::AND32mi8: return X86::AND32mi;
243   case X86::AND64ri8: return X86::AND64ri32;
244   case X86::AND64mi8: return X86::AND64mi32;
245 
246     // OR
247   case X86::OR16ri8: return X86::OR16ri;
248   case X86::OR16mi8: return X86::OR16mi;
249   case X86::OR32ri8: return X86::OR32ri;
250   case X86::OR32mi8: return X86::OR32mi;
251   case X86::OR64ri8: return X86::OR64ri32;
252   case X86::OR64mi8: return X86::OR64mi32;
253 
254     // XOR
255   case X86::XOR16ri8: return X86::XOR16ri;
256   case X86::XOR16mi8: return X86::XOR16mi;
257   case X86::XOR32ri8: return X86::XOR32ri;
258   case X86::XOR32mi8: return X86::XOR32mi;
259   case X86::XOR64ri8: return X86::XOR64ri32;
260   case X86::XOR64mi8: return X86::XOR64mi32;
261 
262     // ADD
263   case X86::ADD16ri8: return X86::ADD16ri;
264   case X86::ADD16mi8: return X86::ADD16mi;
265   case X86::ADD32ri8: return X86::ADD32ri;
266   case X86::ADD32mi8: return X86::ADD32mi;
267   case X86::ADD64ri8: return X86::ADD64ri32;
268   case X86::ADD64mi8: return X86::ADD64mi32;
269 
270    // ADC
271   case X86::ADC16ri8: return X86::ADC16ri;
272   case X86::ADC16mi8: return X86::ADC16mi;
273   case X86::ADC32ri8: return X86::ADC32ri;
274   case X86::ADC32mi8: return X86::ADC32mi;
275   case X86::ADC64ri8: return X86::ADC64ri32;
276   case X86::ADC64mi8: return X86::ADC64mi32;
277 
278     // SUB
279   case X86::SUB16ri8: return X86::SUB16ri;
280   case X86::SUB16mi8: return X86::SUB16mi;
281   case X86::SUB32ri8: return X86::SUB32ri;
282   case X86::SUB32mi8: return X86::SUB32mi;
283   case X86::SUB64ri8: return X86::SUB64ri32;
284   case X86::SUB64mi8: return X86::SUB64mi32;
285 
286    // SBB
287   case X86::SBB16ri8: return X86::SBB16ri;
288   case X86::SBB16mi8: return X86::SBB16mi;
289   case X86::SBB32ri8: return X86::SBB32ri;
290   case X86::SBB32mi8: return X86::SBB32mi;
291   case X86::SBB64ri8: return X86::SBB64ri32;
292   case X86::SBB64mi8: return X86::SBB64mi32;
293 
294     // CMP
295   case X86::CMP16ri8: return X86::CMP16ri;
296   case X86::CMP16mi8: return X86::CMP16mi;
297   case X86::CMP32ri8: return X86::CMP32ri;
298   case X86::CMP32mi8: return X86::CMP32mi;
299   case X86::CMP64ri8: return X86::CMP64ri32;
300   case X86::CMP64mi8: return X86::CMP64mi32;
301 
302     // PUSH
303   case X86::PUSH32i8:  return X86::PUSHi32;
304   case X86::PUSH16i8:  return X86::PUSHi16;
305   case X86::PUSH64i8:  return X86::PUSH64i32;
306   }
307 }
308 
309 static unsigned getRelaxedOpcode(const MCInst &Inst, bool Is16BitMode) {
310   unsigned R = getRelaxedOpcodeArith(Inst);
311   if (R != Inst.getOpcode())
312     return R;
313   return getRelaxedOpcodeBranch(Inst, Is16BitMode);
314 }
315 
316 static X86::CondCode getCondFromBranch(const MCInst &MI,
317                                        const MCInstrInfo &MCII) {
318   unsigned Opcode = MI.getOpcode();
319   switch (Opcode) {
320   default:
321     return X86::COND_INVALID;
322   case X86::JCC_1: {
323     const MCInstrDesc &Desc = MCII.get(Opcode);
324     return static_cast<X86::CondCode>(
325         MI.getOperand(Desc.getNumOperands() - 1).getImm());
326   }
327   }
328 }
329 
330 static X86::SecondMacroFusionInstKind
331 classifySecondInstInMacroFusion(const MCInst &MI, const MCInstrInfo &MCII) {
332   X86::CondCode CC = getCondFromBranch(MI, MCII);
333   return classifySecondCondCodeInMacroFusion(CC);
334 }
335 
336 /// Check if the instruction uses RIP relative addressing.
337 static bool isRIPRelative(const MCInst &MI, const MCInstrInfo &MCII) {
338   unsigned Opcode = MI.getOpcode();
339   const MCInstrDesc &Desc = MCII.get(Opcode);
340   uint64_t TSFlags = Desc.TSFlags;
341   unsigned CurOp = X86II::getOperandBias(Desc);
342   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
343   if (MemoryOperand < 0)
344     return false;
345   unsigned BaseRegNum = MemoryOperand + CurOp + X86::AddrBaseReg;
346   unsigned BaseReg = MI.getOperand(BaseRegNum).getReg();
347   return (BaseReg == X86::RIP);
348 }
349 
350 /// Check if the instruction is a prefix.
351 static bool isPrefix(const MCInst &MI, const MCInstrInfo &MCII) {
352   return X86II::isPrefix(MCII.get(MI.getOpcode()).TSFlags);
353 }
354 
355 /// Check if the instruction is valid as the first instruction in macro fusion.
356 static bool isFirstMacroFusibleInst(const MCInst &Inst,
357                                     const MCInstrInfo &MCII) {
358   // An Intel instruction with RIP relative addressing is not macro fusible.
359   if (isRIPRelative(Inst, MCII))
360     return false;
361   X86::FirstMacroFusionInstKind FIK =
362       X86::classifyFirstOpcodeInMacroFusion(Inst.getOpcode());
363   return FIK != X86::FirstMacroFusionInstKind::Invalid;
364 }
365 
366 /// X86 can reduce the bytes of NOP by padding instructions with prefixes to
367 /// get a better peformance in some cases. Here, we determine which prefix is
368 /// the most suitable.
369 ///
370 /// If the instruction has a segment override prefix, use the existing one.
371 /// If the target is 64-bit, use the CS.
372 /// If the target is 32-bit,
373 ///   - If the instruction has a ESP/EBP base register, use SS.
374 ///   - Otherwise use DS.
375 uint8_t X86AsmBackend::determinePaddingPrefix(const MCInst &Inst) const {
376   assert((STI.hasFeature(X86::Mode32Bit) || STI.hasFeature(X86::Mode64Bit)) &&
377          "Prefixes can be added only in 32-bit or 64-bit mode.");
378   const MCInstrDesc &Desc = MCII->get(Inst.getOpcode());
379   uint64_t TSFlags = Desc.TSFlags;
380 
381   // Determine where the memory operand starts, if present.
382   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
383   if (MemoryOperand != -1)
384     MemoryOperand += X86II::getOperandBias(Desc);
385 
386   unsigned SegmentReg = 0;
387   if (MemoryOperand >= 0) {
388     // Check for explicit segment override on memory operand.
389     SegmentReg = Inst.getOperand(MemoryOperand + X86::AddrSegmentReg).getReg();
390   }
391 
392   switch (TSFlags & X86II::FormMask) {
393   default:
394     break;
395   case X86II::RawFrmDstSrc: {
396     // Check segment override opcode prefix as needed (not for %ds).
397     if (Inst.getOperand(2).getReg() != X86::DS)
398       SegmentReg = Inst.getOperand(2).getReg();
399     break;
400   }
401   case X86II::RawFrmSrc: {
402     // Check segment override opcode prefix as needed (not for %ds).
403     if (Inst.getOperand(1).getReg() != X86::DS)
404       SegmentReg = Inst.getOperand(1).getReg();
405     break;
406   }
407   case X86II::RawFrmMemOffs: {
408     // Check segment override opcode prefix as needed.
409     SegmentReg = Inst.getOperand(1).getReg();
410     break;
411   }
412   }
413 
414   if (SegmentReg != 0)
415     return X86::getSegmentOverridePrefixForReg(SegmentReg);
416 
417   if (STI.hasFeature(X86::Mode64Bit))
418     return X86::CS_Encoding;
419 
420   if (MemoryOperand >= 0) {
421     unsigned BaseRegNum = MemoryOperand + X86::AddrBaseReg;
422     unsigned BaseReg = Inst.getOperand(BaseRegNum).getReg();
423     if (BaseReg == X86::ESP || BaseReg == X86::EBP)
424       return X86::SS_Encoding;
425   }
426   return X86::DS_Encoding;
427 }
428 
429 /// Check if the two instructions will be macro-fused on the target cpu.
430 bool X86AsmBackend::isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const {
431   const MCInstrDesc &InstDesc = MCII->get(Jcc.getOpcode());
432   if (!InstDesc.isConditionalBranch())
433     return false;
434   if (!isFirstMacroFusibleInst(Cmp, *MCII))
435     return false;
436   const X86::FirstMacroFusionInstKind CmpKind =
437       X86::classifyFirstOpcodeInMacroFusion(Cmp.getOpcode());
438   const X86::SecondMacroFusionInstKind BranchKind =
439       classifySecondInstInMacroFusion(Jcc, *MCII);
440   return X86::isMacroFused(CmpKind, BranchKind);
441 }
442 
443 /// Check if the instruction has a variant symbol operand.
444 static bool hasVariantSymbol(const MCInst &MI) {
445   for (auto &Operand : MI) {
446     if (!Operand.isExpr())
447       continue;
448     const MCExpr &Expr = *Operand.getExpr();
449     if (Expr.getKind() == MCExpr::SymbolRef &&
450         cast<MCSymbolRefExpr>(Expr).getKind() != MCSymbolRefExpr::VK_None)
451       return true;
452   }
453   return false;
454 }
455 
456 bool X86AsmBackend::allowAutoPadding() const {
457   return (AlignBoundary != Align(1) && AlignBranchType != X86::AlignBranchNone);
458 }
459 
460 bool X86AsmBackend::needAlign(MCObjectStreamer &OS) const {
461   if (!OS.getAllowAutoPadding())
462     return false;
463   assert(allowAutoPadding() && "incorrect initialization!");
464 
465   // To be Done: Currently don't deal with Bundle cases.
466   if (OS.getAssembler().isBundlingEnabled())
467     return false;
468 
469   // Branches only need to be aligned in 32-bit or 64-bit mode.
470   if (!(STI.hasFeature(X86::Mode64Bit) || STI.hasFeature(X86::Mode32Bit)))
471     return false;
472 
473   return true;
474 }
475 
476 /// X86 has certain instructions which enable interrupts exactly one
477 /// instruction *after* the instruction which stores to SS.  Return true if the
478 /// given instruction has such an interrupt delay slot.
479 static bool hasInterruptDelaySlot(const MCInst &Inst) {
480   switch (Inst.getOpcode()) {
481   case X86::POPSS16:
482   case X86::POPSS32:
483   case X86::STI:
484     return true;
485 
486   case X86::MOV16sr:
487   case X86::MOV32sr:
488   case X86::MOV64sr:
489   case X86::MOV16sm:
490     if (Inst.getOperand(0).getReg() == X86::SS)
491       return true;
492     break;
493   }
494   return false;
495 }
496 
497 /// Check if the instruction to be emitted is right after any data.
498 static bool
499 isRightAfterData(MCFragment *CurrentFragment,
500                  const std::pair<MCFragment *, size_t> &PrevInstPosition) {
501   MCFragment *F = CurrentFragment;
502   // Empty data fragments may be created to prevent further data being
503   // added into the previous fragment, we need to skip them since they
504   // have no contents.
505   for (; isa_and_nonnull<MCDataFragment>(F); F = F->getPrevNode())
506     if (cast<MCDataFragment>(F)->getContents().size() != 0)
507       break;
508 
509   // Since data is always emitted into a DataFragment, our check strategy is
510   // simple here.
511   //   - If the fragment is a DataFragment
512   //     - If it's not the fragment where the previous instruction is,
513   //       returns true.
514   //     - If it's the fragment holding the previous instruction but its
515   //       size changed since the the previous instruction was emitted into
516   //       it, returns true.
517   //     - Otherwise returns false.
518   //   - If the fragment is not a DataFragment, returns false.
519   if (auto *DF = dyn_cast_or_null<MCDataFragment>(F))
520     return DF != PrevInstPosition.first ||
521            DF->getContents().size() != PrevInstPosition.second;
522 
523   return false;
524 }
525 
526 /// \returns the fragment size if it has instructions, otherwise returns 0.
527 static size_t getSizeForInstFragment(const MCFragment *F) {
528   if (!F || !F->hasInstructions())
529     return 0;
530   // MCEncodedFragmentWithContents being templated makes this tricky.
531   switch (F->getKind()) {
532   default:
533     llvm_unreachable("Unknown fragment with instructions!");
534   case MCFragment::FT_Data:
535     return cast<MCDataFragment>(*F).getContents().size();
536   case MCFragment::FT_Relaxable:
537     return cast<MCRelaxableFragment>(*F).getContents().size();
538   case MCFragment::FT_CompactEncodedInst:
539     return cast<MCCompactEncodedInstFragment>(*F).getContents().size();
540   }
541 }
542 
543 /// Check if the instruction operand needs to be aligned.
544 bool X86AsmBackend::needAlignInst(const MCInst &Inst) const {
545   const MCInstrDesc &InstDesc = MCII->get(Inst.getOpcode());
546   return (InstDesc.isConditionalBranch() &&
547           (AlignBranchType & X86::AlignBranchJcc)) ||
548          (InstDesc.isUnconditionalBranch() &&
549           (AlignBranchType & X86::AlignBranchJmp)) ||
550          (InstDesc.isCall() &&
551           (AlignBranchType & X86::AlignBranchCall)) ||
552          (InstDesc.isReturn() &&
553           (AlignBranchType & X86::AlignBranchRet)) ||
554          (InstDesc.isIndirectBranch() &&
555           (AlignBranchType & X86::AlignBranchIndirect));
556 }
557 
558 /// Return true if we can insert NOP or prefixes automatically before the
559 /// the instruction to be emitted.
560 bool X86AsmBackend::allowAutoPaddingForInst(const MCInst &Inst,
561                                             MCObjectStreamer &OS) const {
562   if (hasVariantSymbol(Inst))
563     // Linker may rewrite the instruction with variant symbol operand(e.g.
564     // TLSCALL).
565     return false;
566 
567   if (hasInterruptDelaySlot(PrevInst))
568     // If this instruction follows an interrupt enabling instruction with a one
569     // instruction delay, inserting a nop would change behavior.
570     return false;
571 
572   if (isPrefix(PrevInst, *MCII))
573     // If this instruction follows a prefix, inserting a nop/prefix would change
574     // semantic.
575     return false;
576 
577   if (isPrefix(Inst, *MCII))
578     // If this instruction is a prefix, inserting a prefix would change
579     // semantic.
580     return false;
581 
582   if (isRightAfterData(OS.getCurrentFragment(), PrevInstPosition))
583     // If this instruction follows any data, there is no clear
584     // instruction boundary, inserting a nop/prefix would change semantic.
585     return false;
586 
587   return true;
588 }
589 
590 /// Insert BoundaryAlignFragment before instructions to align branches.
591 void X86AsmBackend::emitInstructionBegin(MCObjectStreamer &OS,
592                                          const MCInst &Inst) {
593   AllowAutoPaddingForInst = allowAutoPaddingForInst(Inst, OS);
594 
595   if (!needAlign(OS))
596     return;
597 
598   if (!isMacroFused(PrevInst, Inst))
599     // Macro fusion doesn't happen indeed, clear the pending.
600     PendingBoundaryAlign = nullptr;
601 
602   if (!AllowAutoPaddingForInst)
603     return;
604 
605   if (PendingBoundaryAlign &&
606       OS.getCurrentFragment()->getPrevNode() == PendingBoundaryAlign) {
607     // Macro fusion actually happens and there is no other fragment inserted
608     // after the previous instruction.
609     //
610     // Do nothing here since we already inserted a BoudaryAlign fragment when
611     // we met the first instruction in the fused pair and we'll tie them
612     // together in emitInstructionEnd.
613     //
614     // Note: When there is at least one fragment, such as MCAlignFragment,
615     // inserted after the previous instruction, e.g.
616     //
617     // \code
618     //   cmp %rax %rcx
619     //   .align 16
620     //   je .Label0
621     // \ endcode
622     //
623     // We will treat the JCC as a unfused branch although it may be fused
624     // with the CMP.
625     return;
626   }
627 
628   if (needAlignInst(Inst) || ((AlignBranchType & X86::AlignBranchFused) &&
629                               isFirstMacroFusibleInst(Inst, *MCII))) {
630     // If we meet a unfused branch or the first instuction in a fusiable pair,
631     // insert a BoundaryAlign fragment.
632     OS.insert(PendingBoundaryAlign =
633                   new MCBoundaryAlignFragment(AlignBoundary));
634   }
635 }
636 
637 /// Set the last fragment to be aligned for the BoundaryAlignFragment.
638 void X86AsmBackend::emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst) {
639   PrevInst = Inst;
640   MCFragment *CF = OS.getCurrentFragment();
641   PrevInstPosition = std::make_pair(CF, getSizeForInstFragment(CF));
642   if (auto *F = dyn_cast_or_null<MCRelaxableFragment>(CF))
643     F->setAllowAutoPadding(AllowAutoPaddingForInst);
644 
645   if (!needAlign(OS))
646     return;
647 
648   if (!needAlignInst(Inst) || !PendingBoundaryAlign)
649     return;
650 
651   // Tie the aligned instructions into a a pending BoundaryAlign.
652   PendingBoundaryAlign->setLastFragment(CF);
653   PendingBoundaryAlign = nullptr;
654 
655   // We need to ensure that further data isn't added to the current
656   // DataFragment, so that we can get the size of instructions later in
657   // MCAssembler::relaxBoundaryAlign. The easiest way is to insert a new empty
658   // DataFragment.
659   if (isa_and_nonnull<MCDataFragment>(CF))
660     OS.insert(new MCDataFragment());
661 
662   // Update the maximum alignment on the current section if necessary.
663   MCSection *Sec = OS.getCurrentSectionOnly();
664   if (AlignBoundary.value() > Sec->getAlignment())
665     Sec->setAlignment(AlignBoundary);
666 }
667 
668 Optional<MCFixupKind> X86AsmBackend::getFixupKind(StringRef Name) const {
669   if (STI.getTargetTriple().isOSBinFormatELF()) {
670     unsigned Type;
671     if (STI.getTargetTriple().getArch() == Triple::x86_64) {
672       Type = llvm::StringSwitch<unsigned>(Name)
673 #define ELF_RELOC(X, Y) .Case(#X, Y)
674 #include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
675 #undef ELF_RELOC
676                  .Default(-1u);
677     } else {
678       Type = llvm::StringSwitch<unsigned>(Name)
679 #define ELF_RELOC(X, Y) .Case(#X, Y)
680 #include "llvm/BinaryFormat/ELFRelocs/i386.def"
681 #undef ELF_RELOC
682                  .Default(-1u);
683     }
684     if (Type == -1u)
685       return None;
686     return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
687   }
688   return MCAsmBackend::getFixupKind(Name);
689 }
690 
691 const MCFixupKindInfo &X86AsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
692   const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
693       {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
694       {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
695       {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
696       {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
697       {"reloc_signed_4byte", 0, 32, 0},
698       {"reloc_signed_4byte_relax", 0, 32, 0},
699       {"reloc_global_offset_table", 0, 32, 0},
700       {"reloc_global_offset_table8", 0, 64, 0},
701       {"reloc_branch_4byte_pcrel", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
702   };
703 
704   // Fixup kinds from .reloc directive are like R_386_NONE/R_X86_64_NONE. They
705   // do not require any extra processing.
706   if (Kind >= FirstLiteralRelocationKind)
707     return MCAsmBackend::getFixupKindInfo(FK_NONE);
708 
709   if (Kind < FirstTargetFixupKind)
710     return MCAsmBackend::getFixupKindInfo(Kind);
711 
712   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
713          "Invalid kind!");
714   assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
715   return Infos[Kind - FirstTargetFixupKind];
716 }
717 
718 bool X86AsmBackend::shouldForceRelocation(const MCAssembler &,
719                                           const MCFixup &Fixup,
720                                           const MCValue &) {
721   return Fixup.getKind() >= FirstLiteralRelocationKind;
722 }
723 
724 static unsigned getFixupKindSize(unsigned Kind) {
725   switch (Kind) {
726   default:
727     llvm_unreachable("invalid fixup kind!");
728   case FK_NONE:
729     return 0;
730   case FK_PCRel_1:
731   case FK_SecRel_1:
732   case FK_Data_1:
733     return 1;
734   case FK_PCRel_2:
735   case FK_SecRel_2:
736   case FK_Data_2:
737     return 2;
738   case FK_PCRel_4:
739   case X86::reloc_riprel_4byte:
740   case X86::reloc_riprel_4byte_relax:
741   case X86::reloc_riprel_4byte_relax_rex:
742   case X86::reloc_riprel_4byte_movq_load:
743   case X86::reloc_signed_4byte:
744   case X86::reloc_signed_4byte_relax:
745   case X86::reloc_global_offset_table:
746   case X86::reloc_branch_4byte_pcrel:
747   case FK_SecRel_4:
748   case FK_Data_4:
749     return 4;
750   case FK_PCRel_8:
751   case FK_SecRel_8:
752   case FK_Data_8:
753   case X86::reloc_global_offset_table8:
754     return 8;
755   }
756 }
757 
758 void X86AsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
759                                const MCValue &Target,
760                                MutableArrayRef<char> Data,
761                                uint64_t Value, bool IsResolved,
762                                const MCSubtargetInfo *STI) const {
763   unsigned Kind = Fixup.getKind();
764   if (Kind >= FirstLiteralRelocationKind)
765     return;
766   unsigned Size = getFixupKindSize(Kind);
767 
768   assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
769 
770   int64_t SignedValue = static_cast<int64_t>(Value);
771   if ((Target.isAbsolute() || IsResolved) &&
772       getFixupKindInfo(Fixup.getKind()).Flags &
773       MCFixupKindInfo::FKF_IsPCRel) {
774     // check that PC relative fixup fits into the fixup size.
775     if (Size > 0 && !isIntN(Size * 8, SignedValue))
776       Asm.getContext().reportError(
777                                    Fixup.getLoc(), "value of " + Twine(SignedValue) +
778                                    " is too large for field of " + Twine(Size) +
779                                    ((Size == 1) ? " byte." : " bytes."));
780   } else {
781     // Check that uppper bits are either all zeros or all ones.
782     // Specifically ignore overflow/underflow as long as the leakage is
783     // limited to the lower bits. This is to remain compatible with
784     // other assemblers.
785     assert((Size == 0 || isIntN(Size * 8 + 1, SignedValue)) &&
786            "Value does not fit in the Fixup field");
787   }
788 
789   for (unsigned i = 0; i != Size; ++i)
790     Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
791 }
792 
793 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst,
794                                       const MCSubtargetInfo &STI) const {
795   // Branches can always be relaxed in either mode.
796   if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
797     return true;
798 
799   // Check if this instruction is ever relaxable.
800   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
801     return false;
802 
803 
804   // Check if the relaxable operand has an expression. For the current set of
805   // relaxable instructions, the relaxable operand is always the last operand.
806   unsigned RelaxableOp = Inst.getNumOperands() - 1;
807   if (Inst.getOperand(RelaxableOp).isExpr())
808     return true;
809 
810   return false;
811 }
812 
813 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
814                                          uint64_t Value,
815                                          const MCRelaxableFragment *DF,
816                                          const MCAsmLayout &Layout) const {
817   // Relax if the value is too big for a (signed) i8.
818   return !isInt<8>(Value);
819 }
820 
821 // FIXME: Can tblgen help at all here to verify there aren't other instructions
822 // we can relax?
823 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
824                                      const MCSubtargetInfo &STI,
825                                      MCInst &Res) const {
826   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
827   bool Is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
828   unsigned RelaxedOp = getRelaxedOpcode(Inst, Is16BitMode);
829 
830   if (RelaxedOp == Inst.getOpcode()) {
831     SmallString<256> Tmp;
832     raw_svector_ostream OS(Tmp);
833     Inst.dump_pretty(OS);
834     OS << "\n";
835     report_fatal_error("unexpected instruction to relax: " + OS.str());
836   }
837 
838   Res = Inst;
839   Res.setOpcode(RelaxedOp);
840 }
841 
842 /// Return true if this instruction has been fully relaxed into it's most
843 /// general available form.
844 static bool isFullyRelaxed(const MCRelaxableFragment &RF) {
845   auto &Inst = RF.getInst();
846   auto &STI = *RF.getSubtargetInfo();
847   bool Is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
848   return getRelaxedOpcode(Inst, Is16BitMode) == Inst.getOpcode();
849 }
850 
851 static unsigned getRemainingPrefixSize(const MCInst &Inst,
852                                        const MCSubtargetInfo &STI,
853                                        MCCodeEmitter &Emitter) {
854   SmallString<256> Code;
855   raw_svector_ostream VecOS(Code);
856   Emitter.emitPrefix(Inst, VecOS, STI);
857   assert(Code.size() < 15 && "The number of prefixes must be less than 15.");
858 
859   // TODO: It turns out we need a decent amount of plumbing for the target
860   // specific bits to determine number of prefixes its safe to add.  Various
861   // targets (older chips mostly, but also Atom family) encounter decoder
862   // stalls with too many prefixes.  For testing purposes, we set the value
863   // externally for the moment.
864   unsigned ExistingPrefixSize = Code.size();
865   unsigned TargetPrefixMax = X86PadMaxPrefixSize;
866   if (TargetPrefixMax <= ExistingPrefixSize)
867     return 0;
868   return TargetPrefixMax - ExistingPrefixSize;
869 }
870 
871 bool X86AsmBackend::padInstructionViaPrefix(MCRelaxableFragment &RF,
872                                             MCCodeEmitter &Emitter,
873                                             unsigned &RemainingSize) const {
874   if (!RF.getAllowAutoPadding())
875     return false;
876   // If the instruction isn't fully relaxed, shifting it around might require a
877   // larger value for one of the fixups then can be encoded.  The outer loop
878   // will also catch this before moving to the next instruction, but we need to
879   // prevent padding this single instruction as well.
880   if (!isFullyRelaxed(RF))
881     return false;
882 
883   const unsigned OldSize = RF.getContents().size();
884   if (OldSize == 15)
885     return false;
886 
887   const unsigned MaxPossiblePad = std::min(15 - OldSize, RemainingSize);
888   const unsigned PrefixBytesToAdd =
889     std::min(MaxPossiblePad,
890              getRemainingPrefixSize(RF.getInst(), STI, Emitter));
891   if (PrefixBytesToAdd == 0)
892     return false;
893 
894   const uint8_t Prefix = determinePaddingPrefix(RF.getInst());
895 
896   SmallString<256> Code;
897   Code.append(PrefixBytesToAdd, Prefix);
898   Code.append(RF.getContents().begin(), RF.getContents().end());
899   RF.getContents() = Code;
900 
901   // Adjust the fixups for the change in offsets
902   for (auto &F : RF.getFixups()) {
903     F.setOffset(F.getOffset() + PrefixBytesToAdd);
904   }
905 
906   RemainingSize -= PrefixBytesToAdd;
907   return true;
908 }
909 
910 bool X86AsmBackend::padInstructionViaRelaxation(MCRelaxableFragment &RF,
911                                                 MCCodeEmitter &Emitter,
912                                                 unsigned &RemainingSize) const {
913   if (isFullyRelaxed(RF))
914     // TODO: There are lots of other tricks we could apply for increasing
915     // encoding size without impacting performance.
916     return false;
917 
918   MCInst Relaxed;
919   relaxInstruction(RF.getInst(), *RF.getSubtargetInfo(), Relaxed);
920 
921   SmallVector<MCFixup, 4> Fixups;
922   SmallString<15> Code;
923   raw_svector_ostream VecOS(Code);
924   Emitter.encodeInstruction(Relaxed, VecOS, Fixups, *RF.getSubtargetInfo());
925   const unsigned OldSize = RF.getContents().size();
926   const unsigned NewSize = Code.size();
927   assert(NewSize >= OldSize && "size decrease during relaxation?");
928   unsigned Delta = NewSize - OldSize;
929   if (Delta > RemainingSize)
930     return false;
931   RF.setInst(Relaxed);
932   RF.getContents() = Code;
933   RF.getFixups() = Fixups;
934   RemainingSize -= Delta;
935   return true;
936 }
937 
938 bool X86AsmBackend::padInstructionEncoding(MCRelaxableFragment &RF,
939                                            MCCodeEmitter &Emitter,
940                                            unsigned &RemainingSize) const {
941   bool Changed = false;
942   if (RemainingSize != 0)
943     Changed |= padInstructionViaRelaxation(RF, Emitter, RemainingSize);
944   if (RemainingSize != 0)
945     Changed |= padInstructionViaPrefix(RF, Emitter, RemainingSize);
946   return Changed;
947 }
948 
949 void X86AsmBackend::finishLayout(MCAssembler const &Asm,
950                                  MCAsmLayout &Layout) const {
951   // See if we can further relax some instructions to cut down on the number of
952   // nop bytes required for code alignment.  The actual win is in reducing
953   // instruction count, not number of bytes.  Modern X86-64 can easily end up
954   // decode limited.  It is often better to reduce the number of instructions
955   // (i.e. eliminate nops) even at the cost of increasing the size and
956   // complexity of others.
957   if (!X86PadForAlign && !X86PadForBranchAlign)
958     return;
959 
960   DenseSet<MCFragment *> LabeledFragments;
961   for (const MCSymbol &S : Asm.symbols())
962     LabeledFragments.insert(S.getFragment(false));
963 
964   for (MCSection &Sec : Asm) {
965     if (!Sec.getKind().isText())
966       continue;
967 
968     SmallVector<MCRelaxableFragment *, 4> Relaxable;
969     for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
970       MCFragment &F = *I;
971 
972       if (LabeledFragments.count(&F))
973         Relaxable.clear();
974 
975       if (F.getKind() == MCFragment::FT_Data ||
976           F.getKind() == MCFragment::FT_CompactEncodedInst)
977         // Skip and ignore
978         continue;
979 
980       if (F.getKind() == MCFragment::FT_Relaxable) {
981         auto &RF = cast<MCRelaxableFragment>(*I);
982         Relaxable.push_back(&RF);
983         continue;
984       }
985 
986       auto canHandle = [](MCFragment &F) -> bool {
987         switch (F.getKind()) {
988         default:
989           return false;
990         case MCFragment::FT_Align:
991           return X86PadForAlign;
992         case MCFragment::FT_BoundaryAlign:
993           return X86PadForBranchAlign;
994         }
995       };
996       // For any unhandled kind, assume we can't change layout.
997       if (!canHandle(F)) {
998         Relaxable.clear();
999         continue;
1000       }
1001 
1002 #ifndef NDEBUG
1003       const uint64_t OrigOffset = Layout.getFragmentOffset(&F);
1004 #endif
1005       const uint64_t OrigSize = Asm.computeFragmentSize(Layout, F);
1006 
1007       // To keep the effects local, prefer to relax instructions closest to
1008       // the align directive.  This is purely about human understandability
1009       // of the resulting code.  If we later find a reason to expand
1010       // particular instructions over others, we can adjust.
1011       MCFragment *FirstChangedFragment = nullptr;
1012       unsigned RemainingSize = OrigSize;
1013       while (!Relaxable.empty() && RemainingSize != 0) {
1014         auto &RF = *Relaxable.pop_back_val();
1015         // Give the backend a chance to play any tricks it wishes to increase
1016         // the encoding size of the given instruction.  Target independent code
1017         // will try further relaxation, but target's may play further tricks.
1018         if (padInstructionEncoding(RF, Asm.getEmitter(), RemainingSize))
1019           FirstChangedFragment = &RF;
1020 
1021         // If we have an instruction which hasn't been fully relaxed, we can't
1022         // skip past it and insert bytes before it.  Changing its starting
1023         // offset might require a larger negative offset than it can encode.
1024         // We don't need to worry about larger positive offsets as none of the
1025         // possible offsets between this and our align are visible, and the
1026         // ones afterwards aren't changing.
1027         if (!isFullyRelaxed(RF))
1028           break;
1029       }
1030       Relaxable.clear();
1031 
1032       if (FirstChangedFragment) {
1033         // Make sure the offsets for any fragments in the effected range get
1034         // updated.  Note that this (conservatively) invalidates the offsets of
1035         // those following, but this is not required.
1036         Layout.invalidateFragmentsFrom(FirstChangedFragment);
1037       }
1038 
1039       // BoundaryAlign explicitly tracks it's size (unlike align)
1040       if (F.getKind() == MCFragment::FT_BoundaryAlign)
1041         cast<MCBoundaryAlignFragment>(F).setSize(RemainingSize);
1042 
1043 #ifndef NDEBUG
1044       const uint64_t FinalOffset = Layout.getFragmentOffset(&F);
1045       const uint64_t FinalSize = Asm.computeFragmentSize(Layout, F);
1046       assert(OrigOffset + OrigSize == FinalOffset + FinalSize &&
1047              "can't move start of next fragment!");
1048       assert(FinalSize == RemainingSize && "inconsistent size computation?");
1049 #endif
1050 
1051       // If we're looking at a boundary align, make sure we don't try to pad
1052       // its target instructions for some following directive.  Doing so would
1053       // break the alignment of the current boundary align.
1054       if (auto *BF = dyn_cast<MCBoundaryAlignFragment>(&F)) {
1055         const MCFragment *LastFragment = BF->getLastFragment();
1056         if (!LastFragment)
1057           continue;
1058         while (&*I != LastFragment)
1059           ++I;
1060       }
1061     }
1062   }
1063 
1064   // The layout is done. Mark every fragment as valid.
1065   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1066     MCSection &Section = *Layout.getSectionOrder()[i];
1067     Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1068     Asm.computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1069   }
1070 }
1071 
1072 /// Write a sequence of optimal nops to the output, covering \p Count
1073 /// bytes.
1074 /// \return - true on success, false on failure
1075 bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
1076   static const char Nops[10][11] = {
1077     // nop
1078     "\x90",
1079     // xchg %ax,%ax
1080     "\x66\x90",
1081     // nopl (%[re]ax)
1082     "\x0f\x1f\x00",
1083     // nopl 0(%[re]ax)
1084     "\x0f\x1f\x40\x00",
1085     // nopl 0(%[re]ax,%[re]ax,1)
1086     "\x0f\x1f\x44\x00\x00",
1087     // nopw 0(%[re]ax,%[re]ax,1)
1088     "\x66\x0f\x1f\x44\x00\x00",
1089     // nopl 0L(%[re]ax)
1090     "\x0f\x1f\x80\x00\x00\x00\x00",
1091     // nopl 0L(%[re]ax,%[re]ax,1)
1092     "\x0f\x1f\x84\x00\x00\x00\x00\x00",
1093     // nopw 0L(%[re]ax,%[re]ax,1)
1094     "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
1095     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1096     "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
1097   };
1098 
1099   // This CPU doesn't support long nops. If needed add more.
1100   // FIXME: We could generated something better than plain 0x90.
1101   if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
1102     for (uint64_t i = 0; i < Count; ++i)
1103       OS << '\x90';
1104     return true;
1105   }
1106 
1107   // 15-bytes is the longest single NOP instruction, but 10-bytes is
1108   // commonly the longest that can be efficiently decoded.
1109   uint64_t MaxNopLength = 10;
1110   if (STI.getFeatureBits()[X86::FeatureFast7ByteNOP])
1111     MaxNopLength = 7;
1112   else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
1113     MaxNopLength = 15;
1114   else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
1115     MaxNopLength = 11;
1116 
1117   // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
1118   // length.
1119   do {
1120     const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
1121     const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
1122     for (uint8_t i = 0; i < Prefixes; i++)
1123       OS << '\x66';
1124     const uint8_t Rest = ThisNopLength - Prefixes;
1125     if (Rest != 0)
1126       OS.write(Nops[Rest - 1], Rest);
1127     Count -= ThisNopLength;
1128   } while (Count != 0);
1129 
1130   return true;
1131 }
1132 
1133 /* *** */
1134 
1135 namespace {
1136 
1137 class ELFX86AsmBackend : public X86AsmBackend {
1138 public:
1139   uint8_t OSABI;
1140   ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
1141       : X86AsmBackend(T, STI), OSABI(OSABI) {}
1142 };
1143 
1144 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
1145 public:
1146   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
1147                       const MCSubtargetInfo &STI)
1148     : ELFX86AsmBackend(T, OSABI, STI) {}
1149 
1150   std::unique_ptr<MCObjectTargetWriter>
1151   createObjectTargetWriter() const override {
1152     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
1153   }
1154 };
1155 
1156 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
1157 public:
1158   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
1159                        const MCSubtargetInfo &STI)
1160       : ELFX86AsmBackend(T, OSABI, STI) {}
1161 
1162   std::unique_ptr<MCObjectTargetWriter>
1163   createObjectTargetWriter() const override {
1164     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1165                                     ELF::EM_X86_64);
1166   }
1167 };
1168 
1169 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
1170 public:
1171   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
1172                          const MCSubtargetInfo &STI)
1173       : ELFX86AsmBackend(T, OSABI, STI) {}
1174 
1175   std::unique_ptr<MCObjectTargetWriter>
1176   createObjectTargetWriter() const override {
1177     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1178                                     ELF::EM_IAMCU);
1179   }
1180 };
1181 
1182 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
1183 public:
1184   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
1185                       const MCSubtargetInfo &STI)
1186     : ELFX86AsmBackend(T, OSABI, STI) {}
1187 
1188   std::unique_ptr<MCObjectTargetWriter>
1189   createObjectTargetWriter() const override {
1190     return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
1191   }
1192 };
1193 
1194 class WindowsX86AsmBackend : public X86AsmBackend {
1195   bool Is64Bit;
1196 
1197 public:
1198   WindowsX86AsmBackend(const Target &T, bool is64Bit,
1199                        const MCSubtargetInfo &STI)
1200     : X86AsmBackend(T, STI)
1201     , Is64Bit(is64Bit) {
1202   }
1203 
1204   Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
1205     return StringSwitch<Optional<MCFixupKind>>(Name)
1206         .Case("dir32", FK_Data_4)
1207         .Case("secrel32", FK_SecRel_4)
1208         .Case("secidx", FK_SecRel_2)
1209         .Default(MCAsmBackend::getFixupKind(Name));
1210   }
1211 
1212   std::unique_ptr<MCObjectTargetWriter>
1213   createObjectTargetWriter() const override {
1214     return createX86WinCOFFObjectWriter(Is64Bit);
1215   }
1216 };
1217 
1218 namespace CU {
1219 
1220   /// Compact unwind encoding values.
1221   enum CompactUnwindEncodings {
1222     /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
1223     /// the return address, then [RE]SP is moved to [RE]BP.
1224     UNWIND_MODE_BP_FRAME                   = 0x01000000,
1225 
1226     /// A frameless function with a small constant stack size.
1227     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
1228 
1229     /// A frameless function with a large constant stack size.
1230     UNWIND_MODE_STACK_IND                  = 0x03000000,
1231 
1232     /// No compact unwind encoding is available.
1233     UNWIND_MODE_DWARF                      = 0x04000000,
1234 
1235     /// Mask for encoding the frame registers.
1236     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
1237 
1238     /// Mask for encoding the frameless registers.
1239     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
1240   };
1241 
1242 } // end CU namespace
1243 
1244 class DarwinX86AsmBackend : public X86AsmBackend {
1245   const MCRegisterInfo &MRI;
1246 
1247   /// Number of registers that can be saved in a compact unwind encoding.
1248   enum { CU_NUM_SAVED_REGS = 6 };
1249 
1250   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
1251   Triple TT;
1252   bool Is64Bit;
1253 
1254   unsigned OffsetSize;                   ///< Offset of a "push" instruction.
1255   unsigned MoveInstrSize;                ///< Size of a "move" instruction.
1256   unsigned StackDivide;                  ///< Amount to adjust stack size by.
1257 protected:
1258   /// Size of a "push" instruction for the given register.
1259   unsigned PushInstrSize(unsigned Reg) const {
1260     switch (Reg) {
1261       case X86::EBX:
1262       case X86::ECX:
1263       case X86::EDX:
1264       case X86::EDI:
1265       case X86::ESI:
1266       case X86::EBP:
1267       case X86::RBX:
1268       case X86::RBP:
1269         return 1;
1270       case X86::R12:
1271       case X86::R13:
1272       case X86::R14:
1273       case X86::R15:
1274         return 2;
1275     }
1276     return 1;
1277   }
1278 
1279 private:
1280   /// Get the compact unwind number for a given register. The number
1281   /// corresponds to the enum lists in compact_unwind_encoding.h.
1282   int getCompactUnwindRegNum(unsigned Reg) const {
1283     static const MCPhysReg CU32BitRegs[7] = {
1284       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
1285     };
1286     static const MCPhysReg CU64BitRegs[] = {
1287       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
1288     };
1289     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
1290     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
1291       if (*CURegs == Reg)
1292         return Idx;
1293 
1294     return -1;
1295   }
1296 
1297   /// Return the registers encoded for a compact encoding with a frame
1298   /// pointer.
1299   uint32_t encodeCompactUnwindRegistersWithFrame() const {
1300     // Encode the registers in the order they were saved --- 3-bits per
1301     // register. The list of saved registers is assumed to be in reverse
1302     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
1303     uint32_t RegEnc = 0;
1304     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
1305       unsigned Reg = SavedRegs[i];
1306       if (Reg == 0) break;
1307 
1308       int CURegNum = getCompactUnwindRegNum(Reg);
1309       if (CURegNum == -1) return ~0U;
1310 
1311       // Encode the 3-bit register number in order, skipping over 3-bits for
1312       // each register.
1313       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
1314     }
1315 
1316     assert((RegEnc & 0x3FFFF) == RegEnc &&
1317            "Invalid compact register encoding!");
1318     return RegEnc;
1319   }
1320 
1321   /// Create the permutation encoding used with frameless stacks. It is
1322   /// passed the number of registers to be saved and an array of the registers
1323   /// saved.
1324   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
1325     // The saved registers are numbered from 1 to 6. In order to encode the
1326     // order in which they were saved, we re-number them according to their
1327     // place in the register order. The re-numbering is relative to the last
1328     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
1329     // that order:
1330     //
1331     //    Orig  Re-Num
1332     //    ----  ------
1333     //     6       6
1334     //     2       2
1335     //     4       3
1336     //     5       3
1337     //
1338     for (unsigned i = 0; i < RegCount; ++i) {
1339       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
1340       if (CUReg == -1) return ~0U;
1341       SavedRegs[i] = CUReg;
1342     }
1343 
1344     // Reverse the list.
1345     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
1346 
1347     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
1348     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
1349       unsigned Countless = 0;
1350       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
1351         if (SavedRegs[j] < SavedRegs[i])
1352           ++Countless;
1353 
1354       RenumRegs[i] = SavedRegs[i] - Countless - 1;
1355     }
1356 
1357     // Take the renumbered values and encode them into a 10-bit number.
1358     uint32_t permutationEncoding = 0;
1359     switch (RegCount) {
1360     case 6:
1361       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
1362                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
1363                              +     RenumRegs[4];
1364       break;
1365     case 5:
1366       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
1367                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
1368                              +     RenumRegs[5];
1369       break;
1370     case 4:
1371       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
1372                              + 3 * RenumRegs[4] +      RenumRegs[5];
1373       break;
1374     case 3:
1375       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
1376                              +     RenumRegs[5];
1377       break;
1378     case 2:
1379       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
1380       break;
1381     case 1:
1382       permutationEncoding |=       RenumRegs[5];
1383       break;
1384     }
1385 
1386     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
1387            "Invalid compact register encoding!");
1388     return permutationEncoding;
1389   }
1390 
1391 public:
1392   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
1393                       const MCSubtargetInfo &STI)
1394       : X86AsmBackend(T, STI), MRI(MRI), TT(STI.getTargetTriple()),
1395         Is64Bit(TT.isArch64Bit()) {
1396     memset(SavedRegs, 0, sizeof(SavedRegs));
1397     OffsetSize = Is64Bit ? 8 : 4;
1398     MoveInstrSize = Is64Bit ? 3 : 2;
1399     StackDivide = Is64Bit ? 8 : 4;
1400   }
1401 
1402   std::unique_ptr<MCObjectTargetWriter>
1403   createObjectTargetWriter() const override {
1404     uint32_t CPUType = cantFail(MachO::getCPUType(TT));
1405     uint32_t CPUSubType = cantFail(MachO::getCPUSubType(TT));
1406     return createX86MachObjectWriter(Is64Bit, CPUType, CPUSubType);
1407   }
1408 
1409   /// Implementation of algorithm to generate the compact unwind encoding
1410   /// for the CFI instructions.
1411   uint32_t
1412   generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const override {
1413     if (Instrs.empty()) return 0;
1414 
1415     // Reset the saved registers.
1416     unsigned SavedRegIdx = 0;
1417     memset(SavedRegs, 0, sizeof(SavedRegs));
1418 
1419     bool HasFP = false;
1420 
1421     // Encode that we are using EBP/RBP as the frame pointer.
1422     uint32_t CompactUnwindEncoding = 0;
1423 
1424     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
1425     unsigned InstrOffset = 0;
1426     unsigned StackAdjust = 0;
1427     unsigned StackSize = 0;
1428     unsigned NumDefCFAOffsets = 0;
1429 
1430     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1431       const MCCFIInstruction &Inst = Instrs[i];
1432 
1433       switch (Inst.getOperation()) {
1434       default:
1435         // Any other CFI directives indicate a frame that we aren't prepared
1436         // to represent via compact unwind, so just bail out.
1437         return 0;
1438       case MCCFIInstruction::OpDefCfaRegister: {
1439         // Defines a frame pointer. E.g.
1440         //
1441         //     movq %rsp, %rbp
1442         //  L0:
1443         //     .cfi_def_cfa_register %rbp
1444         //
1445         HasFP = true;
1446 
1447         // If the frame pointer is other than esp/rsp, we do not have a way to
1448         // generate a compact unwinding representation, so bail out.
1449         if (*MRI.getLLVMRegNum(Inst.getRegister(), true) !=
1450             (Is64Bit ? X86::RBP : X86::EBP))
1451           return 0;
1452 
1453         // Reset the counts.
1454         memset(SavedRegs, 0, sizeof(SavedRegs));
1455         StackAdjust = 0;
1456         SavedRegIdx = 0;
1457         InstrOffset += MoveInstrSize;
1458         break;
1459       }
1460       case MCCFIInstruction::OpDefCfaOffset: {
1461         // Defines a new offset for the CFA. E.g.
1462         //
1463         //  With frame:
1464         //
1465         //     pushq %rbp
1466         //  L0:
1467         //     .cfi_def_cfa_offset 16
1468         //
1469         //  Without frame:
1470         //
1471         //     subq $72, %rsp
1472         //  L0:
1473         //     .cfi_def_cfa_offset 80
1474         //
1475         StackSize = std::abs(Inst.getOffset()) / StackDivide;
1476         ++NumDefCFAOffsets;
1477         break;
1478       }
1479       case MCCFIInstruction::OpOffset: {
1480         // Defines a "push" of a callee-saved register. E.g.
1481         //
1482         //     pushq %r15
1483         //     pushq %r14
1484         //     pushq %rbx
1485         //  L0:
1486         //     subq $120, %rsp
1487         //  L1:
1488         //     .cfi_offset %rbx, -40
1489         //     .cfi_offset %r14, -32
1490         //     .cfi_offset %r15, -24
1491         //
1492         if (SavedRegIdx == CU_NUM_SAVED_REGS)
1493           // If there are too many saved registers, we cannot use a compact
1494           // unwind encoding.
1495           return CU::UNWIND_MODE_DWARF;
1496 
1497         unsigned Reg = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1498         SavedRegs[SavedRegIdx++] = Reg;
1499         StackAdjust += OffsetSize;
1500         InstrOffset += PushInstrSize(Reg);
1501         break;
1502       }
1503       }
1504     }
1505 
1506     StackAdjust /= StackDivide;
1507 
1508     if (HasFP) {
1509       if ((StackAdjust & 0xFF) != StackAdjust)
1510         // Offset was too big for a compact unwind encoding.
1511         return CU::UNWIND_MODE_DWARF;
1512 
1513       // Get the encoding of the saved registers when we have a frame pointer.
1514       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
1515       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1516 
1517       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
1518       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
1519       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
1520     } else {
1521       SubtractInstrIdx += InstrOffset;
1522       ++StackAdjust;
1523 
1524       if ((StackSize & 0xFF) == StackSize) {
1525         // Frameless stack with a small stack size.
1526         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
1527 
1528         // Encode the stack size.
1529         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
1530       } else {
1531         if ((StackAdjust & 0x7) != StackAdjust)
1532           // The extra stack adjustments are too big for us to handle.
1533           return CU::UNWIND_MODE_DWARF;
1534 
1535         // Frameless stack with an offset too large for us to encode compactly.
1536         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
1537 
1538         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
1539         // instruction.
1540         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
1541 
1542         // Encode any extra stack adjustments (done via push instructions).
1543         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
1544       }
1545 
1546       // Encode the number of registers saved. (Reverse the list first.)
1547       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
1548       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
1549 
1550       // Get the encoding of the saved registers when we don't have a frame
1551       // pointer.
1552       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
1553       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1554 
1555       // Encode the register encoding.
1556       CompactUnwindEncoding |=
1557         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
1558     }
1559 
1560     return CompactUnwindEncoding;
1561   }
1562 };
1563 
1564 } // end anonymous namespace
1565 
1566 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
1567                                            const MCSubtargetInfo &STI,
1568                                            const MCRegisterInfo &MRI,
1569                                            const MCTargetOptions &Options) {
1570   const Triple &TheTriple = STI.getTargetTriple();
1571   if (TheTriple.isOSBinFormatMachO())
1572     return new DarwinX86AsmBackend(T, MRI, STI);
1573 
1574   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1575     return new WindowsX86AsmBackend(T, false, STI);
1576 
1577   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1578 
1579   if (TheTriple.isOSIAMCU())
1580     return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
1581 
1582   return new ELFX86_32AsmBackend(T, OSABI, STI);
1583 }
1584 
1585 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
1586                                            const MCSubtargetInfo &STI,
1587                                            const MCRegisterInfo &MRI,
1588                                            const MCTargetOptions &Options) {
1589   const Triple &TheTriple = STI.getTargetTriple();
1590   if (TheTriple.isOSBinFormatMachO())
1591     return new DarwinX86AsmBackend(T, MRI, STI);
1592 
1593   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1594     return new WindowsX86AsmBackend(T, true, STI);
1595 
1596   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1597 
1598   if (TheTriple.getEnvironment() == Triple::GNUX32)
1599     return new ELFX86_X32AsmBackend(T, OSABI, STI);
1600   return new ELFX86_64AsmBackend(T, OSABI, STI);
1601 }
1602