]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/ARMAsmPrinter.cpp
Import DTS files from Linux 4.18
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / ARM / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMAsmPrinter.h"
16 #include "ARM.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMTargetMachine.h"
20 #include "ARMTargetObjectFile.h"
21 #include "InstPrinter/ARMInstPrinter.h"
22 #include "MCTargetDesc/ARMAddressingModes.h"
23 #include "MCTargetDesc/ARMMCExpr.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/BinaryFormat/COFF.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCAssembler.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCELFStreamer.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCObjectStreamer.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/Support/ARMBuildAttributes.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/TargetParser.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetMachine.h"
51 using namespace llvm;
52
53 #define DEBUG_TYPE "asm-printer"
54
55 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
56                              std::unique_ptr<MCStreamer> Streamer)
57     : AsmPrinter(TM, std::move(Streamer)), AFI(nullptr), MCP(nullptr),
58       InConstantPool(false), OptimizationGoals(-1) {}
59
60 void ARMAsmPrinter::EmitFunctionBodyEnd() {
61   // Make sure to terminate any constant pools that were at the end
62   // of the function.
63   if (!InConstantPool)
64     return;
65   InConstantPool = false;
66   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
67 }
68
69 void ARMAsmPrinter::EmitFunctionEntryLabel() {
70   if (AFI->isThumbFunction()) {
71     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
72     OutStreamer->EmitThumbFunc(CurrentFnSym);
73   } else {
74     OutStreamer->EmitAssemblerFlag(MCAF_Code32);
75   }
76   OutStreamer->EmitLabel(CurrentFnSym);
77 }
78
79 void ARMAsmPrinter::EmitXXStructor(const DataLayout &DL, const Constant *CV) {
80   uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
81   assert(Size && "C++ constructor pointer had zero size!");
82
83   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
84   assert(GV && "C++ constructor pointer was not a GlobalValue!");
85
86   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
87                                                            ARMII::MO_NO_FLAG),
88                                             (Subtarget->isTargetELF()
89                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
90                                              : MCSymbolRefExpr::VK_None),
91                                             OutContext);
92
93   OutStreamer->EmitValue(E, Size);
94 }
95
96 void ARMAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
97   if (PromotedGlobals.count(GV))
98     // The global was promoted into a constant pool. It should not be emitted.
99     return;
100   AsmPrinter::EmitGlobalVariable(GV);
101 }
102
103 /// runOnMachineFunction - This uses the EmitInstruction()
104 /// method to print assembly for each instruction.
105 ///
106 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
107   AFI = MF.getInfo<ARMFunctionInfo>();
108   MCP = MF.getConstantPool();
109   Subtarget = &MF.getSubtarget<ARMSubtarget>();
110
111   SetupMachineFunction(MF);
112   const Function &F = MF.getFunction();
113   const TargetMachine& TM = MF.getTarget();
114
115   // Collect all globals that had their storage promoted to a constant pool.
116   // Functions are emitted before variables, so this accumulates promoted
117   // globals from all functions in PromotedGlobals.
118   for (auto *GV : AFI->getGlobalsPromotedToConstantPool())
119     PromotedGlobals.insert(GV);
120   
121   // Calculate this function's optimization goal.
122   unsigned OptimizationGoal;
123   if (F.hasFnAttribute(Attribute::OptimizeNone))
124     // For best debugging illusion, speed and small size sacrificed
125     OptimizationGoal = 6;
126   else if (F.optForMinSize())
127     // Aggressively for small size, speed and debug illusion sacrificed
128     OptimizationGoal = 4;
129   else if (F.optForSize())
130     // For small size, but speed and debugging illusion preserved
131     OptimizationGoal = 3;
132   else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
133     // Aggressively for speed, small size and debug illusion sacrificed
134     OptimizationGoal = 2;
135   else if (TM.getOptLevel() > CodeGenOpt::None)
136     // For speed, but small size and good debug illusion preserved
137     OptimizationGoal = 1;
138   else // TM.getOptLevel() == CodeGenOpt::None
139     // For good debugging, but speed and small size preserved
140     OptimizationGoal = 5;
141
142   // Combine a new optimization goal with existing ones.
143   if (OptimizationGoals == -1) // uninitialized goals
144     OptimizationGoals = OptimizationGoal;
145   else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
146     OptimizationGoals = 0;
147
148   if (Subtarget->isTargetCOFF()) {
149     bool Internal = F.hasInternalLinkage();
150     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
151                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
152     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
153
154     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
155     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
156     OutStreamer->EmitCOFFSymbolType(Type);
157     OutStreamer->EndCOFFSymbolDef();
158   }
159
160   // Emit the rest of the function body.
161   EmitFunctionBody();
162
163   // Emit the XRay table for this function.
164   emitXRayTable();
165
166   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
167   // These are created per function, rather than per TU, since it's
168   // relatively easy to exceed the thumb branch range within a TU.
169   if (! ThumbIndirectPads.empty()) {
170     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
171     EmitAlignment(1);
172     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
173       OutStreamer->EmitLabel(TIP.second);
174       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
175         .addReg(TIP.first)
176         // Add predicate operands.
177         .addImm(ARMCC::AL)
178         .addReg(0));
179     }
180     ThumbIndirectPads.clear();
181   }
182
183   // We didn't modify anything.
184   return false;
185 }
186
187 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
188                                  raw_ostream &O) {
189   const MachineOperand &MO = MI->getOperand(OpNum);
190   unsigned TF = MO.getTargetFlags();
191
192   switch (MO.getType()) {
193   default: llvm_unreachable("<unknown operand type>");
194   case MachineOperand::MO_Register: {
195     unsigned Reg = MO.getReg();
196     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
197     assert(!MO.getSubReg() && "Subregs should be eliminated!");
198     if(ARM::GPRPairRegClass.contains(Reg)) {
199       const MachineFunction &MF = *MI->getParent()->getParent();
200       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
201       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
202     }
203     O << ARMInstPrinter::getRegisterName(Reg);
204     break;
205   }
206   case MachineOperand::MO_Immediate: {
207     int64_t Imm = MO.getImm();
208     O << '#';
209     if (TF == ARMII::MO_LO16)
210       O << ":lower16:";
211     else if (TF == ARMII::MO_HI16)
212       O << ":upper16:";
213     O << Imm;
214     break;
215   }
216   case MachineOperand::MO_MachineBasicBlock:
217     MO.getMBB()->getSymbol()->print(O, MAI);
218     return;
219   case MachineOperand::MO_GlobalAddress: {
220     const GlobalValue *GV = MO.getGlobal();
221     if (TF & ARMII::MO_LO16)
222       O << ":lower16:";
223     else if (TF & ARMII::MO_HI16)
224       O << ":upper16:";
225     GetARMGVSymbol(GV, TF)->print(O, MAI);
226
227     printOffset(MO.getOffset(), O);
228     break;
229   }
230   case MachineOperand::MO_ConstantPoolIndex:
231     if (Subtarget->genExecuteOnly())
232       llvm_unreachable("execute-only should not generate constant pools");
233     GetCPISymbol(MO.getIndex())->print(O, MAI);
234     break;
235   }
236 }
237
238 //===--------------------------------------------------------------------===//
239
240 MCSymbol *ARMAsmPrinter::
241 GetARMJTIPICJumpTableLabel(unsigned uid) const {
242   const DataLayout &DL = getDataLayout();
243   SmallString<60> Name;
244   raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
245                             << getFunctionNumber() << '_' << uid;
246   return OutContext.getOrCreateSymbol(Name);
247 }
248
249 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
250                                     unsigned AsmVariant, const char *ExtraCode,
251                                     raw_ostream &O) {
252   // Does this asm operand have a single letter operand modifier?
253   if (ExtraCode && ExtraCode[0]) {
254     if (ExtraCode[1] != 0) return true; // Unknown modifier.
255
256     switch (ExtraCode[0]) {
257     default:
258       // See if this is a generic print operand
259       return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
260     case 'a': // Print as a memory address.
261       if (MI->getOperand(OpNum).isReg()) {
262         O << "["
263           << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
264           << "]";
265         return false;
266       }
267       LLVM_FALLTHROUGH;
268     case 'c': // Don't print "#" before an immediate operand.
269       if (!MI->getOperand(OpNum).isImm())
270         return true;
271       O << MI->getOperand(OpNum).getImm();
272       return false;
273     case 'P': // Print a VFP double precision register.
274     case 'q': // Print a NEON quad precision register.
275       printOperand(MI, OpNum, O);
276       return false;
277     case 'y': // Print a VFP single precision register as indexed double.
278       if (MI->getOperand(OpNum).isReg()) {
279         unsigned Reg = MI->getOperand(OpNum).getReg();
280         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
281         // Find the 'd' register that has this 's' register as a sub-register,
282         // and determine the lane number.
283         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
284           if (!ARM::DPRRegClass.contains(*SR))
285             continue;
286           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
287           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
288           return false;
289         }
290       }
291       return true;
292     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
293       if (!MI->getOperand(OpNum).isImm())
294         return true;
295       O << ~(MI->getOperand(OpNum).getImm());
296       return false;
297     case 'L': // The low 16 bits of an immediate constant.
298       if (!MI->getOperand(OpNum).isImm())
299         return true;
300       O << (MI->getOperand(OpNum).getImm() & 0xffff);
301       return false;
302     case 'M': { // A register range suitable for LDM/STM.
303       if (!MI->getOperand(OpNum).isReg())
304         return true;
305       const MachineOperand &MO = MI->getOperand(OpNum);
306       unsigned RegBegin = MO.getReg();
307       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
308       // already got the operands in registers that are operands to the
309       // inline asm statement.
310       O << "{";
311       if (ARM::GPRPairRegClass.contains(RegBegin)) {
312         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
313         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
314         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
315         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
316       }
317       O << ARMInstPrinter::getRegisterName(RegBegin);
318
319       // FIXME: The register allocator not only may not have given us the
320       // registers in sequence, but may not be in ascending registers. This
321       // will require changes in the register allocator that'll need to be
322       // propagated down here if the operands change.
323       unsigned RegOps = OpNum + 1;
324       while (MI->getOperand(RegOps).isReg()) {
325         O << ", "
326           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
327         RegOps++;
328       }
329
330       O << "}";
331
332       return false;
333     }
334     case 'R': // The most significant register of a pair.
335     case 'Q': { // The least significant register of a pair.
336       if (OpNum == 0)
337         return true;
338       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
339       if (!FlagsOP.isImm())
340         return true;
341       unsigned Flags = FlagsOP.getImm();
342
343       // This operand may not be the one that actually provides the register. If
344       // it's tied to a previous one then we should refer instead to that one
345       // for registers and their classes.
346       unsigned TiedIdx;
347       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
348         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
349           unsigned OpFlags = MI->getOperand(OpNum).getImm();
350           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
351         }
352         Flags = MI->getOperand(OpNum).getImm();
353
354         // Later code expects OpNum to be pointing at the register rather than
355         // the flags.
356         OpNum += 1;
357       }
358
359       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
360       unsigned RC;
361       InlineAsm::hasRegClassConstraint(Flags, RC);
362       if (RC == ARM::GPRPairRegClassID) {
363         if (NumVals != 1)
364           return true;
365         const MachineOperand &MO = MI->getOperand(OpNum);
366         if (!MO.isReg())
367           return true;
368         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
369         unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
370             ARM::gsub_0 : ARM::gsub_1);
371         O << ARMInstPrinter::getRegisterName(Reg);
372         return false;
373       }
374       if (NumVals != 2)
375         return true;
376       unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
377       if (RegOp >= MI->getNumOperands())
378         return true;
379       const MachineOperand &MO = MI->getOperand(RegOp);
380       if (!MO.isReg())
381         return true;
382       unsigned Reg = MO.getReg();
383       O << ARMInstPrinter::getRegisterName(Reg);
384       return false;
385     }
386
387     case 'e': // The low doubleword register of a NEON quad register.
388     case 'f': { // The high doubleword register of a NEON quad register.
389       if (!MI->getOperand(OpNum).isReg())
390         return true;
391       unsigned Reg = MI->getOperand(OpNum).getReg();
392       if (!ARM::QPRRegClass.contains(Reg))
393         return true;
394       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
395       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
396                                        ARM::dsub_0 : ARM::dsub_1);
397       O << ARMInstPrinter::getRegisterName(SubReg);
398       return false;
399     }
400
401     // This modifier is not yet supported.
402     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
403       return true;
404     case 'H': { // The highest-numbered register of a pair.
405       const MachineOperand &MO = MI->getOperand(OpNum);
406       if (!MO.isReg())
407         return true;
408       const MachineFunction &MF = *MI->getParent()->getParent();
409       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
410       unsigned Reg = MO.getReg();
411       if(!ARM::GPRPairRegClass.contains(Reg))
412         return false;
413       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
414       O << ARMInstPrinter::getRegisterName(Reg);
415       return false;
416     }
417     }
418   }
419
420   printOperand(MI, OpNum, O);
421   return false;
422 }
423
424 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
425                                           unsigned OpNum, unsigned AsmVariant,
426                                           const char *ExtraCode,
427                                           raw_ostream &O) {
428   // Does this asm operand have a single letter operand modifier?
429   if (ExtraCode && ExtraCode[0]) {
430     if (ExtraCode[1] != 0) return true; // Unknown modifier.
431
432     switch (ExtraCode[0]) {
433       case 'A': // A memory operand for a VLD1/VST1 instruction.
434       default: return true;  // Unknown modifier.
435       case 'm': // The base register of a memory operand.
436         if (!MI->getOperand(OpNum).isReg())
437           return true;
438         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
439         return false;
440     }
441   }
442
443   const MachineOperand &MO = MI->getOperand(OpNum);
444   assert(MO.isReg() && "unexpected inline asm memory operand");
445   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
446   return false;
447 }
448
449 static bool isThumb(const MCSubtargetInfo& STI) {
450   return STI.getFeatureBits()[ARM::ModeThumb];
451 }
452
453 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
454                                      const MCSubtargetInfo *EndInfo) const {
455   // If either end mode is unknown (EndInfo == NULL) or different than
456   // the start mode, then restore the start mode.
457   const bool WasThumb = isThumb(StartInfo);
458   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
459     OutStreamer->EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
460   }
461 }
462
463 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
464   const Triple &TT = TM.getTargetTriple();
465   // Use unified assembler syntax.
466   OutStreamer->EmitAssemblerFlag(MCAF_SyntaxUnified);
467
468   // Emit ARM Build Attributes
469   if (TT.isOSBinFormatELF())
470     emitAttributes();
471
472   // Use the triple's architecture and subarchitecture to determine
473   // if we're thumb for the purposes of the top level code16 assembler
474   // flag.
475   if (!M.getModuleInlineAsm().empty() && TT.isThumb())
476     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
477 }
478
479 static void
480 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
481                          MachineModuleInfoImpl::StubValueTy &MCSym) {
482   // L_foo$stub:
483   OutStreamer.EmitLabel(StubLabel);
484   //   .indirect_symbol _foo
485   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
486
487   if (MCSym.getInt())
488     // External to current translation unit.
489     OutStreamer.EmitIntValue(0, 4/*size*/);
490   else
491     // Internal to current translation unit.
492     //
493     // When we place the LSDA into the TEXT section, the type info
494     // pointers need to be indirect and pc-rel. We accomplish this by
495     // using NLPs; however, sometimes the types are local to the file.
496     // We need to fill in the value for the NLP in those cases.
497     OutStreamer.EmitValue(
498         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
499         4 /*size*/);
500 }
501
502
503 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
504   const Triple &TT = TM.getTargetTriple();
505   if (TT.isOSBinFormatMachO()) {
506     // All darwin targets use mach-o.
507     const TargetLoweringObjectFileMachO &TLOFMacho =
508       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
509     MachineModuleInfoMachO &MMIMacho =
510       MMI->getObjFileInfo<MachineModuleInfoMachO>();
511
512     // Output non-lazy-pointers for external and common global variables.
513     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
514
515     if (!Stubs.empty()) {
516       // Switch with ".non_lazy_symbol_pointer" directive.
517       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
518       EmitAlignment(2);
519
520       for (auto &Stub : Stubs)
521         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
522
523       Stubs.clear();
524       OutStreamer->AddBlankLine();
525     }
526
527     Stubs = MMIMacho.GetThreadLocalGVStubList();
528     if (!Stubs.empty()) {
529       // Switch with ".non_lazy_symbol_pointer" directive.
530       OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
531       EmitAlignment(2);
532
533       for (auto &Stub : Stubs)
534         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
535
536       Stubs.clear();
537       OutStreamer->AddBlankLine();
538     }
539
540     // Funny Darwin hack: This flag tells the linker that no global symbols
541     // contain code that falls through to other global symbols (e.g. the obvious
542     // implementation of multiple entry points).  If this doesn't occur, the
543     // linker can safely perform dead code stripping.  Since LLVM never
544     // generates code that does this, it is always safe to set.
545     OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
546   }
547
548   if (TT.isOSBinFormatCOFF()) {
549     const auto &TLOF =
550         static_cast<const TargetLoweringObjectFileCOFF &>(getObjFileLowering());
551
552     std::string Flags;
553     raw_string_ostream OS(Flags);
554
555     for (const auto &Function : M)
556       TLOF.emitLinkerFlagsForGlobal(OS, &Function);
557     for (const auto &Global : M.globals())
558       TLOF.emitLinkerFlagsForGlobal(OS, &Global);
559     for (const auto &Alias : M.aliases())
560       TLOF.emitLinkerFlagsForGlobal(OS, &Alias);
561
562     OS.flush();
563
564     // Output collected flags
565     if (!Flags.empty()) {
566       OutStreamer->SwitchSection(TLOF.getDrectveSection());
567       OutStreamer->EmitBytes(Flags);
568     }
569   }
570
571   // The last attribute to be emitted is ABI_optimization_goals
572   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
573   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
574
575   if (OptimizationGoals > 0 &&
576       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
577        Subtarget->isTargetMuslAEABI()))
578     ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
579   OptimizationGoals = -1;
580
581   ATS.finishAttributeSection();
582 }
583
584 //===----------------------------------------------------------------------===//
585 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
586 // FIXME:
587 // The following seem like one-off assembler flags, but they actually need
588 // to appear in the .ARM.attributes section in ELF.
589 // Instead of subclassing the MCELFStreamer, we do the work here.
590
591 // Returns true if all functions have the same function attribute value.
592 // It also returns true when the module has no functions.
593 static bool checkFunctionsAttributeConsistency(const Module &M, StringRef Attr,
594                                                StringRef Value) {
595   return !any_of(M, [&](const Function &F) {
596     return F.getFnAttribute(Attr).getValueAsString() != Value;
597   });
598 }
599
600 void ARMAsmPrinter::emitAttributes() {
601   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
602   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
603
604   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
605
606   ATS.switchVendor("aeabi");
607
608   // Compute ARM ELF Attributes based on the default subtarget that
609   // we'd have constructed. The existing ARM behavior isn't LTO clean
610   // anyhow.
611   // FIXME: For ifunc related functions we could iterate over and look
612   // for a feature string that doesn't match the default one.
613   const Triple &TT = TM.getTargetTriple();
614   StringRef CPU = TM.getTargetCPU();
615   StringRef FS = TM.getTargetFeatureString();
616   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
617   if (!FS.empty()) {
618     if (!ArchFS.empty())
619       ArchFS = (Twine(ArchFS) + "," + FS).str();
620     else
621       ArchFS = FS;
622   }
623   const ARMBaseTargetMachine &ATM =
624       static_cast<const ARMBaseTargetMachine &>(TM);
625   const ARMSubtarget STI(TT, CPU, ArchFS, ATM, ATM.isLittleEndian());
626
627   // Emit build attributes for the available hardware.
628   ATS.emitTargetAttributes(STI);
629
630   // RW data addressing.
631   if (isPositionIndependent()) {
632     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
633                       ARMBuildAttrs::AddressRWPCRel);
634   } else if (STI.isRWPI()) {
635     // RWPI specific attributes.
636     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
637                       ARMBuildAttrs::AddressRWSBRel);
638   }
639
640   // RO data addressing.
641   if (isPositionIndependent() || STI.isROPI()) {
642     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
643                       ARMBuildAttrs::AddressROPCRel);
644   }
645
646   // GOT use.
647   if (isPositionIndependent()) {
648     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
649                       ARMBuildAttrs::AddressGOT);
650   } else {
651     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
652                       ARMBuildAttrs::AddressDirect);
653   }
654
655   // Set FP Denormals.
656   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
657                                          "denormal-fp-math",
658                                          "preserve-sign") ||
659       TM.Options.FPDenormalMode == FPDenormal::PreserveSign)
660     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
661                       ARMBuildAttrs::PreserveFPSign);
662   else if (checkFunctionsAttributeConsistency(*MMI->getModule(),
663                                               "denormal-fp-math",
664                                               "positive-zero") ||
665            TM.Options.FPDenormalMode == FPDenormal::PositiveZero)
666     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
667                       ARMBuildAttrs::PositiveZero);
668   else if (!TM.Options.UnsafeFPMath)
669     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
670                       ARMBuildAttrs::IEEEDenormals);
671   else {
672     if (!STI.hasVFP2()) {
673       // When the target doesn't have an FPU (by design or
674       // intention), the assumptions made on the software support
675       // mirror that of the equivalent hardware support *if it
676       // existed*. For v7 and better we indicate that denormals are
677       // flushed preserving sign, and for V6 we indicate that
678       // denormals are flushed to positive zero.
679       if (STI.hasV7Ops())
680         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
681                           ARMBuildAttrs::PreserveFPSign);
682     } else if (STI.hasVFP3()) {
683       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
684       // the sign bit of the zero matches the sign bit of the input or
685       // result that is being flushed to zero.
686       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
687                         ARMBuildAttrs::PreserveFPSign);
688     }
689     // For VFPv2 implementations it is implementation defined as
690     // to whether denormals are flushed to positive zero or to
691     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
692     // LLVM has chosen to flush this to positive zero (most likely for
693     // GCC compatibility), so that's the chosen value here (the
694     // absence of its emission implies zero).
695   }
696
697   // Set FP exceptions and rounding
698   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
699                                          "no-trapping-math", "true") ||
700       TM.Options.NoTrappingFPMath)
701     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
702                       ARMBuildAttrs::Not_Allowed);
703   else if (!TM.Options.UnsafeFPMath) {
704     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
705
706     // If the user has permitted this code to choose the IEEE 754
707     // rounding at run-time, emit the rounding attribute.
708     if (TM.Options.HonorSignDependentRoundingFPMathOption)
709       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
710   }
711
712   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
713   // equivalent of GCC's -ffinite-math-only flag.
714   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
715     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
716                       ARMBuildAttrs::Allowed);
717   else
718     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
719                       ARMBuildAttrs::AllowIEEE754);
720
721   // FIXME: add more flags to ARMBuildAttributes.h
722   // 8-bytes alignment stuff.
723   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
724   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
725
726   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
727   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
728     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
729
730   // FIXME: To support emitting this build attribute as GCC does, the
731   // -mfp16-format option and associated plumbing must be
732   // supported. For now the __fp16 type is exposed by default, so this
733   // attribute should be emitted with value 1.
734   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
735                     ARMBuildAttrs::FP16FormatIEEE);
736
737   if (MMI) {
738     if (const Module *SourceModule = MMI->getModule()) {
739       // ABI_PCS_wchar_t to indicate wchar_t width
740       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
741       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
742               SourceModule->getModuleFlag("wchar_size"))) {
743         int WCharWidth = WCharWidthValue->getZExtValue();
744         assert((WCharWidth == 2 || WCharWidth == 4) &&
745                "wchar_t width must be 2 or 4 bytes");
746         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
747       }
748
749       // ABI_enum_size to indicate enum width
750       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
751       //        (all enums contain a value needing 32 bits to encode).
752       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
753               SourceModule->getModuleFlag("min_enum_size"))) {
754         int EnumWidth = EnumWidthValue->getZExtValue();
755         assert((EnumWidth == 1 || EnumWidth == 4) &&
756                "Minimum enum width must be 1 or 4 bytes");
757         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
758         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
759       }
760     }
761   }
762
763   // We currently do not support using R9 as the TLS pointer.
764   if (STI.isRWPI())
765     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
766                       ARMBuildAttrs::R9IsSB);
767   else if (STI.isR9Reserved())
768     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
769                       ARMBuildAttrs::R9Reserved);
770   else
771     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
772                       ARMBuildAttrs::R9IsGPR);
773 }
774
775 //===----------------------------------------------------------------------===//
776
777 static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
778                              unsigned LabelId, MCContext &Ctx) {
779
780   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
781                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
782   return Label;
783 }
784
785 static MCSymbolRefExpr::VariantKind
786 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
787   switch (Modifier) {
788   case ARMCP::no_modifier:
789     return MCSymbolRefExpr::VK_None;
790   case ARMCP::TLSGD:
791     return MCSymbolRefExpr::VK_TLSGD;
792   case ARMCP::TPOFF:
793     return MCSymbolRefExpr::VK_TPOFF;
794   case ARMCP::GOTTPOFF:
795     return MCSymbolRefExpr::VK_GOTTPOFF;
796   case ARMCP::SBREL:
797     return MCSymbolRefExpr::VK_ARM_SBREL;
798   case ARMCP::GOT_PREL:
799     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
800   case ARMCP::SECREL:
801     return MCSymbolRefExpr::VK_SECREL;
802   }
803   llvm_unreachable("Invalid ARMCPModifier!");
804 }
805
806 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
807                                         unsigned char TargetFlags) {
808   if (Subtarget->isTargetMachO()) {
809     bool IsIndirect =
810         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
811
812     if (!IsIndirect)
813       return getSymbol(GV);
814
815     // FIXME: Remove this when Darwin transition to @GOT like syntax.
816     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
817     MachineModuleInfoMachO &MMIMachO =
818       MMI->getObjFileInfo<MachineModuleInfoMachO>();
819     MachineModuleInfoImpl::StubValueTy &StubSym =
820         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
821                             : MMIMachO.getGVStubEntry(MCSym);
822
823     if (!StubSym.getPointer())
824       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
825                                                    !GV->hasInternalLinkage());
826     return MCSym;
827   } else if (Subtarget->isTargetCOFF()) {
828     assert(Subtarget->isTargetWindows() &&
829            "Windows is the only supported COFF target");
830
831     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
832     if (!IsIndirect)
833       return getSymbol(GV);
834
835     SmallString<128> Name;
836     Name = "__imp_";
837     getNameWithPrefix(Name, GV);
838
839     return OutContext.getOrCreateSymbol(Name);
840   } else if (Subtarget->isTargetELF()) {
841     return getSymbol(GV);
842   }
843   llvm_unreachable("unexpected target");
844 }
845
846 void ARMAsmPrinter::
847 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
848   const DataLayout &DL = getDataLayout();
849   int Size = DL.getTypeAllocSize(MCPV->getType());
850
851   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
852
853   if (ACPV->isPromotedGlobal()) {
854     // This constant pool entry is actually a global whose storage has been
855     // promoted into the constant pool. This global may be referenced still
856     // by debug information, and due to the way AsmPrinter is set up, the debug
857     // info is immutable by the time we decide to promote globals to constant
858     // pools. Because of this, we need to ensure we emit a symbol for the global
859     // with private linkage (the default) so debug info can refer to it.
860     //
861     // However, if this global is promoted into several functions we must ensure
862     // we don't try and emit duplicate symbols!
863     auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
864     for (const auto *GV : ACPC->promotedGlobals()) {
865       if (!EmittedPromotedGlobalLabels.count(GV)) {
866         MCSymbol *GVSym = getSymbol(GV);
867         OutStreamer->EmitLabel(GVSym);
868         EmittedPromotedGlobalLabels.insert(GV);
869       }
870     }
871     return EmitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
872   }
873
874   MCSymbol *MCSym;
875   if (ACPV->isLSDA()) {
876     MCSym = getCurExceptionSym();
877   } else if (ACPV->isBlockAddress()) {
878     const BlockAddress *BA =
879       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
880     MCSym = GetBlockAddressSymbol(BA);
881   } else if (ACPV->isGlobalValue()) {
882     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
883
884     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
885     // flag the global as MO_NONLAZY.
886     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
887     MCSym = GetARMGVSymbol(GV, TF);
888   } else if (ACPV->isMachineBasicBlock()) {
889     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
890     MCSym = MBB->getSymbol();
891   } else {
892     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
893     auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
894     MCSym = GetExternalSymbolSymbol(Sym);
895   }
896
897   // Create an MCSymbol for the reference.
898   const MCExpr *Expr =
899     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
900                             OutContext);
901
902   if (ACPV->getPCAdjustment()) {
903     MCSymbol *PCLabel =
904         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
905                     ACPV->getLabelId(), OutContext);
906     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
907     PCRelExpr =
908       MCBinaryExpr::createAdd(PCRelExpr,
909                               MCConstantExpr::create(ACPV->getPCAdjustment(),
910                                                      OutContext),
911                               OutContext);
912     if (ACPV->mustAddCurrentAddress()) {
913       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
914       // label, so just emit a local label end reference that instead.
915       MCSymbol *DotSym = OutContext.createTempSymbol();
916       OutStreamer->EmitLabel(DotSym);
917       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
918       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
919     }
920     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
921   }
922   OutStreamer->EmitValue(Expr, Size);
923 }
924
925 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
926   const MachineOperand &MO1 = MI->getOperand(1);
927   unsigned JTI = MO1.getIndex();
928
929   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
930   // ARM mode tables.
931   EmitAlignment(2);
932
933   // Emit a label for the jump table.
934   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
935   OutStreamer->EmitLabel(JTISymbol);
936
937   // Mark the jump table as data-in-code.
938   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
939
940   // Emit each entry of the table.
941   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
942   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
943   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
944
945   for (MachineBasicBlock *MBB : JTBBs) {
946     // Construct an MCExpr for the entry. We want a value of the form:
947     // (BasicBlockAddr - TableBeginAddr)
948     //
949     // For example, a table with entries jumping to basic blocks BB0 and BB1
950     // would look like:
951     // LJTI_0_0:
952     //    .word (LBB0 - LJTI_0_0)
953     //    .word (LBB1 - LJTI_0_0)
954     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
955
956     if (isPositionIndependent() || Subtarget->isROPI())
957       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
958                                                                    OutContext),
959                                      OutContext);
960     // If we're generating a table of Thumb addresses in static relocation
961     // model, we need to add one to keep interworking correctly.
962     else if (AFI->isThumbFunction())
963       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
964                                      OutContext);
965     OutStreamer->EmitValue(Expr, 4);
966   }
967   // Mark the end of jump table data-in-code region.
968   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
969 }
970
971 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
972   const MachineOperand &MO1 = MI->getOperand(1);
973   unsigned JTI = MO1.getIndex();
974
975   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
976   // ARM mode tables.
977   EmitAlignment(2);
978
979   // Emit a label for the jump table.
980   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
981   OutStreamer->EmitLabel(JTISymbol);
982
983   // Emit each entry of the table.
984   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
985   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
986   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
987
988   for (MachineBasicBlock *MBB : JTBBs) {
989     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
990                                                           OutContext);
991     // If this isn't a TBB or TBH, the entries are direct branch instructions.
992     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
993         .addExpr(MBBSymbolExpr)
994         .addImm(ARMCC::AL)
995         .addReg(0));
996   }
997 }
998
999 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
1000                                         unsigned OffsetWidth) {
1001   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1002   const MachineOperand &MO1 = MI->getOperand(1);
1003   unsigned JTI = MO1.getIndex();
1004
1005   if (Subtarget->isThumb1Only())
1006     EmitAlignment(2);
1007   
1008   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1009   OutStreamer->EmitLabel(JTISymbol);
1010
1011   // Emit each entry of the table.
1012   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1013   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1014   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1015
1016   // Mark the jump table as data-in-code.
1017   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1018                                                : MCDR_DataRegionJT16);
1019
1020   for (auto MBB : JTBBs) {
1021     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1022                                                           OutContext);
1023     // Otherwise it's an offset from the dispatch instruction. Construct an
1024     // MCExpr for the entry. We want a value of the form:
1025     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1026     //
1027     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1028     // would look like:
1029     // LJTI_0_0:
1030     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1031     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1032     // where LCPI0_0 is a label defined just before the TBB instruction using
1033     // this table.
1034     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1035     const MCExpr *Expr = MCBinaryExpr::createAdd(
1036         MCSymbolRefExpr::create(TBInstPC, OutContext),
1037         MCConstantExpr::create(4, OutContext), OutContext);
1038     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1039     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1040                                    OutContext);
1041     OutStreamer->EmitValue(Expr, OffsetWidth);
1042   }
1043   // Mark the end of jump table data-in-code region. 32-bit offsets use
1044   // actual branch instructions here, so we don't mark those as a data-region
1045   // at all.
1046   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1047
1048   // Make sure the next instruction is 2-byte aligned.
1049   EmitAlignment(1);
1050 }
1051
1052 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1053   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1054       "Only instruction which are involved into frame setup code are allowed");
1055
1056   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1057   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1058   const MachineFunction &MF = *MI->getParent()->getParent();
1059   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1060   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1061
1062   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1063   unsigned Opc = MI->getOpcode();
1064   unsigned SrcReg, DstReg;
1065
1066   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1067     // Two special cases:
1068     // 1) tPUSH does not have src/dst regs.
1069     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1070     // load. Yes, this is pretty fragile, but for now I don't see better
1071     // way... :(
1072     SrcReg = DstReg = ARM::SP;
1073   } else {
1074     SrcReg = MI->getOperand(1).getReg();
1075     DstReg = MI->getOperand(0).getReg();
1076   }
1077
1078   // Try to figure out the unwinding opcode out of src / dst regs.
1079   if (MI->mayStore()) {
1080     // Register saves.
1081     assert(DstReg == ARM::SP &&
1082            "Only stack pointer as a destination reg is supported");
1083
1084     SmallVector<unsigned, 4> RegList;
1085     // Skip src & dst reg, and pred ops.
1086     unsigned StartOp = 2 + 2;
1087     // Use all the operands.
1088     unsigned NumOffset = 0;
1089
1090     switch (Opc) {
1091     default:
1092       MI->print(errs());
1093       llvm_unreachable("Unsupported opcode for unwinding information");
1094     case ARM::tPUSH:
1095       // Special case here: no src & dst reg, but two extra imp ops.
1096       StartOp = 2; NumOffset = 2;
1097       LLVM_FALLTHROUGH;
1098     case ARM::STMDB_UPD:
1099     case ARM::t2STMDB_UPD:
1100     case ARM::VSTMDDB_UPD:
1101       assert(SrcReg == ARM::SP &&
1102              "Only stack pointer as a source reg is supported");
1103       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1104            i != NumOps; ++i) {
1105         const MachineOperand &MO = MI->getOperand(i);
1106         // Actually, there should never be any impdef stuff here. Skip it
1107         // temporary to workaround PR11902.
1108         if (MO.isImplicit())
1109           continue;
1110         RegList.push_back(MO.getReg());
1111       }
1112       break;
1113     case ARM::STR_PRE_IMM:
1114     case ARM::STR_PRE_REG:
1115     case ARM::t2STR_PRE:
1116       assert(MI->getOperand(2).getReg() == ARM::SP &&
1117              "Only stack pointer as a source reg is supported");
1118       RegList.push_back(SrcReg);
1119       break;
1120     }
1121     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1122       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1123   } else {
1124     // Changes of stack / frame pointer.
1125     if (SrcReg == ARM::SP) {
1126       int64_t Offset = 0;
1127       switch (Opc) {
1128       default:
1129         MI->print(errs());
1130         llvm_unreachable("Unsupported opcode for unwinding information");
1131       case ARM::MOVr:
1132       case ARM::tMOVr:
1133         Offset = 0;
1134         break;
1135       case ARM::ADDri:
1136       case ARM::t2ADDri:
1137         Offset = -MI->getOperand(2).getImm();
1138         break;
1139       case ARM::SUBri:
1140       case ARM::t2SUBri:
1141         Offset = MI->getOperand(2).getImm();
1142         break;
1143       case ARM::tSUBspi:
1144         Offset = MI->getOperand(2).getImm()*4;
1145         break;
1146       case ARM::tADDspi:
1147       case ARM::tADDrSPi:
1148         Offset = -MI->getOperand(2).getImm()*4;
1149         break;
1150       case ARM::tLDRpci: {
1151         // Grab the constpool index and check, whether it corresponds to
1152         // original or cloned constpool entry.
1153         unsigned CPI = MI->getOperand(1).getIndex();
1154         const MachineConstantPool *MCP = MF.getConstantPool();
1155         if (CPI >= MCP->getConstants().size())
1156           CPI = AFI.getOriginalCPIdx(CPI);
1157         assert(CPI != -1U && "Invalid constpool index");
1158
1159         // Derive the actual offset.
1160         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1161         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1162         // FIXME: Check for user, it should be "add" instruction!
1163         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1164         break;
1165       }
1166       }
1167
1168       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1169         if (DstReg == FramePtr && FramePtr != ARM::SP)
1170           // Set-up of the frame pointer. Positive values correspond to "add"
1171           // instruction.
1172           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1173         else if (DstReg == ARM::SP) {
1174           // Change of SP by an offset. Positive values correspond to "sub"
1175           // instruction.
1176           ATS.emitPad(Offset);
1177         } else {
1178           // Move of SP to a register.  Positive values correspond to an "add"
1179           // instruction.
1180           ATS.emitMovSP(DstReg, -Offset);
1181         }
1182       }
1183     } else if (DstReg == ARM::SP) {
1184       MI->print(errs());
1185       llvm_unreachable("Unsupported opcode for unwinding information");
1186     }
1187     else {
1188       MI->print(errs());
1189       llvm_unreachable("Unsupported opcode for unwinding information");
1190     }
1191   }
1192 }
1193
1194 // Simple pseudo-instructions have their lowering (with expansion to real
1195 // instructions) auto-generated.
1196 #include "ARMGenMCPseudoLowering.inc"
1197
1198 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1199   const DataLayout &DL = getDataLayout();
1200   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1201   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1202
1203   const MachineFunction &MF = *MI->getParent()->getParent();
1204   const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
1205   unsigned FramePtr = STI.useR7AsFramePointer() ? ARM::R7 : ARM::R11;
1206
1207   // If we just ended a constant pool, mark it as such.
1208   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1209     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1210     InConstantPool = false;
1211   }
1212
1213   // Emit unwinding stuff for frame-related instructions
1214   if (Subtarget->isTargetEHABICompatible() &&
1215        MI->getFlag(MachineInstr::FrameSetup))
1216     EmitUnwindingInstruction(MI);
1217
1218   // Do any auto-generated pseudo lowerings.
1219   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1220     return;
1221
1222   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1223          "Pseudo flag setting opcode should be expanded early");
1224
1225   // Check for manual lowerings.
1226   unsigned Opc = MI->getOpcode();
1227   switch (Opc) {
1228   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1229   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1230   case ARM::LEApcrel:
1231   case ARM::tLEApcrel:
1232   case ARM::t2LEApcrel: {
1233     // FIXME: Need to also handle globals and externals
1234     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1235     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1236                                                ARM::t2LEApcrel ? ARM::t2ADR
1237                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1238                      : ARM::ADR))
1239       .addReg(MI->getOperand(0).getReg())
1240       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1241       // Add predicate operands.
1242       .addImm(MI->getOperand(2).getImm())
1243       .addReg(MI->getOperand(3).getReg()));
1244     return;
1245   }
1246   case ARM::LEApcrelJT:
1247   case ARM::tLEApcrelJT:
1248   case ARM::t2LEApcrelJT: {
1249     MCSymbol *JTIPICSymbol =
1250       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1251     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1252                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1253                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1254                      : ARM::ADR))
1255       .addReg(MI->getOperand(0).getReg())
1256       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1257       // Add predicate operands.
1258       .addImm(MI->getOperand(2).getImm())
1259       .addReg(MI->getOperand(3).getReg()));
1260     return;
1261   }
1262   // Darwin call instructions are just normal call instructions with different
1263   // clobber semantics (they clobber R9).
1264   case ARM::BX_CALL: {
1265     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1266       .addReg(ARM::LR)
1267       .addReg(ARM::PC)
1268       // Add predicate operands.
1269       .addImm(ARMCC::AL)
1270       .addReg(0)
1271       // Add 's' bit operand (always reg0 for this)
1272       .addReg(0));
1273
1274     assert(Subtarget->hasV4TOps());
1275     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1276       .addReg(MI->getOperand(0).getReg()));
1277     return;
1278   }
1279   case ARM::tBX_CALL: {
1280     if (Subtarget->hasV5TOps())
1281       llvm_unreachable("Expected BLX to be selected for v5t+");
1282
1283     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1284     // that the saved lr has its LSB set correctly (the arch doesn't
1285     // have blx).
1286     // So here we generate a bl to a small jump pad that does bx rN.
1287     // The jump pads are emitted after the function body.
1288
1289     unsigned TReg = MI->getOperand(0).getReg();
1290     MCSymbol *TRegSym = nullptr;
1291     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
1292       if (TIP.first == TReg) {
1293         TRegSym = TIP.second;
1294         break;
1295       }
1296     }
1297
1298     if (!TRegSym) {
1299       TRegSym = OutContext.createTempSymbol();
1300       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1301     }
1302
1303     // Create a link-saving branch to the Reg Indirect Jump Pad.
1304     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1305         // Predicate comes first here.
1306         .addImm(ARMCC::AL).addReg(0)
1307         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1308     return;
1309   }
1310   case ARM::BMOVPCRX_CALL: {
1311     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1312       .addReg(ARM::LR)
1313       .addReg(ARM::PC)
1314       // Add predicate operands.
1315       .addImm(ARMCC::AL)
1316       .addReg(0)
1317       // Add 's' bit operand (always reg0 for this)
1318       .addReg(0));
1319
1320     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1321       .addReg(ARM::PC)
1322       .addReg(MI->getOperand(0).getReg())
1323       // Add predicate operands.
1324       .addImm(ARMCC::AL)
1325       .addReg(0)
1326       // Add 's' bit operand (always reg0 for this)
1327       .addReg(0));
1328     return;
1329   }
1330   case ARM::BMOVPCB_CALL: {
1331     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1332       .addReg(ARM::LR)
1333       .addReg(ARM::PC)
1334       // Add predicate operands.
1335       .addImm(ARMCC::AL)
1336       .addReg(0)
1337       // Add 's' bit operand (always reg0 for this)
1338       .addReg(0));
1339
1340     const MachineOperand &Op = MI->getOperand(0);
1341     const GlobalValue *GV = Op.getGlobal();
1342     const unsigned TF = Op.getTargetFlags();
1343     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1344     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1345     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1346       .addExpr(GVSymExpr)
1347       // Add predicate operands.
1348       .addImm(ARMCC::AL)
1349       .addReg(0));
1350     return;
1351   }
1352   case ARM::MOVi16_ga_pcrel:
1353   case ARM::t2MOVi16_ga_pcrel: {
1354     MCInst TmpInst;
1355     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1356     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1357
1358     unsigned TF = MI->getOperand(1).getTargetFlags();
1359     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1360     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1361     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1362
1363     MCSymbol *LabelSym =
1364         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1365                     MI->getOperand(2).getImm(), OutContext);
1366     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1367     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1368     const MCExpr *PCRelExpr =
1369       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1370                                       MCBinaryExpr::createAdd(LabelSymExpr,
1371                                       MCConstantExpr::create(PCAdj, OutContext),
1372                                       OutContext), OutContext), OutContext);
1373       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1374
1375     // Add predicate operands.
1376     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1377     TmpInst.addOperand(MCOperand::createReg(0));
1378     // Add 's' bit operand (always reg0 for this)
1379     TmpInst.addOperand(MCOperand::createReg(0));
1380     EmitToStreamer(*OutStreamer, TmpInst);
1381     return;
1382   }
1383   case ARM::MOVTi16_ga_pcrel:
1384   case ARM::t2MOVTi16_ga_pcrel: {
1385     MCInst TmpInst;
1386     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1387                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1388     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1389     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1390
1391     unsigned TF = MI->getOperand(2).getTargetFlags();
1392     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1393     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1394     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1395
1396     MCSymbol *LabelSym =
1397         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1398                     MI->getOperand(3).getImm(), OutContext);
1399     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1400     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1401     const MCExpr *PCRelExpr =
1402         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1403                                    MCBinaryExpr::createAdd(LabelSymExpr,
1404                                       MCConstantExpr::create(PCAdj, OutContext),
1405                                           OutContext), OutContext), OutContext);
1406       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1407     // Add predicate operands.
1408     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1409     TmpInst.addOperand(MCOperand::createReg(0));
1410     // Add 's' bit operand (always reg0 for this)
1411     TmpInst.addOperand(MCOperand::createReg(0));
1412     EmitToStreamer(*OutStreamer, TmpInst);
1413     return;
1414   }
1415   case ARM::tPICADD: {
1416     // This is a pseudo op for a label + instruction sequence, which looks like:
1417     // LPC0:
1418     //     add r0, pc
1419     // This adds the address of LPC0 to r0.
1420
1421     // Emit the label.
1422     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1423                                        getFunctionNumber(),
1424                                        MI->getOperand(2).getImm(), OutContext));
1425
1426     // Form and emit the add.
1427     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1428       .addReg(MI->getOperand(0).getReg())
1429       .addReg(MI->getOperand(0).getReg())
1430       .addReg(ARM::PC)
1431       // Add predicate operands.
1432       .addImm(ARMCC::AL)
1433       .addReg(0));
1434     return;
1435   }
1436   case ARM::PICADD: {
1437     // This is a pseudo op for a label + instruction sequence, which looks like:
1438     // LPC0:
1439     //     add r0, pc, r0
1440     // This adds the address of LPC0 to r0.
1441
1442     // Emit the label.
1443     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1444                                        getFunctionNumber(),
1445                                        MI->getOperand(2).getImm(), OutContext));
1446
1447     // Form and emit the add.
1448     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1449       .addReg(MI->getOperand(0).getReg())
1450       .addReg(ARM::PC)
1451       .addReg(MI->getOperand(1).getReg())
1452       // Add predicate operands.
1453       .addImm(MI->getOperand(3).getImm())
1454       .addReg(MI->getOperand(4).getReg())
1455       // Add 's' bit operand (always reg0 for this)
1456       .addReg(0));
1457     return;
1458   }
1459   case ARM::PICSTR:
1460   case ARM::PICSTRB:
1461   case ARM::PICSTRH:
1462   case ARM::PICLDR:
1463   case ARM::PICLDRB:
1464   case ARM::PICLDRH:
1465   case ARM::PICLDRSB:
1466   case ARM::PICLDRSH: {
1467     // This is a pseudo op for a label + instruction sequence, which looks like:
1468     // LPC0:
1469     //     OP r0, [pc, r0]
1470     // The LCP0 label is referenced by a constant pool entry in order to get
1471     // a PC-relative address at the ldr instruction.
1472
1473     // Emit the label.
1474     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1475                                        getFunctionNumber(),
1476                                        MI->getOperand(2).getImm(), OutContext));
1477
1478     // Form and emit the load
1479     unsigned Opcode;
1480     switch (MI->getOpcode()) {
1481     default:
1482       llvm_unreachable("Unexpected opcode!");
1483     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1484     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1485     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1486     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1487     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1488     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1489     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1490     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1491     }
1492     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1493       .addReg(MI->getOperand(0).getReg())
1494       .addReg(ARM::PC)
1495       .addReg(MI->getOperand(1).getReg())
1496       .addImm(0)
1497       // Add predicate operands.
1498       .addImm(MI->getOperand(3).getImm())
1499       .addReg(MI->getOperand(4).getReg()));
1500
1501     return;
1502   }
1503   case ARM::CONSTPOOL_ENTRY: {
1504     if (Subtarget->genExecuteOnly())
1505       llvm_unreachable("execute-only should not generate constant pools");
1506
1507     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1508     /// in the function.  The first operand is the ID# for this instruction, the
1509     /// second is the index into the MachineConstantPool that this is, the third
1510     /// is the size in bytes of this constant pool entry.
1511     /// The required alignment is specified on the basic block holding this MI.
1512     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1513     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1514
1515     // If this is the first entry of the pool, mark it.
1516     if (!InConstantPool) {
1517       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1518       InConstantPool = true;
1519     }
1520
1521     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1522
1523     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1524     if (MCPE.isMachineConstantPoolEntry())
1525       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1526     else
1527       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1528     return;
1529   }
1530   case ARM::JUMPTABLE_ADDRS:
1531     EmitJumpTableAddrs(MI);
1532     return;
1533   case ARM::JUMPTABLE_INSTS:
1534     EmitJumpTableInsts(MI);
1535     return;
1536   case ARM::JUMPTABLE_TBB:
1537   case ARM::JUMPTABLE_TBH:
1538     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1539     return;
1540   case ARM::t2BR_JT: {
1541     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1542       .addReg(ARM::PC)
1543       .addReg(MI->getOperand(0).getReg())
1544       // Add predicate operands.
1545       .addImm(ARMCC::AL)
1546       .addReg(0));
1547     return;
1548   }
1549   case ARM::t2TBB_JT:
1550   case ARM::t2TBH_JT: {
1551     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1552     // Lower and emit the PC label, then the instruction itself.
1553     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1554     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1555                                      .addReg(MI->getOperand(0).getReg())
1556                                      .addReg(MI->getOperand(1).getReg())
1557                                      // Add predicate operands.
1558                                      .addImm(ARMCC::AL)
1559                                      .addReg(0));
1560     return;
1561   }
1562   case ARM::tTBB_JT:
1563   case ARM::tTBH_JT: {
1564
1565     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1566     unsigned Base = MI->getOperand(0).getReg();
1567     unsigned Idx = MI->getOperand(1).getReg();
1568     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1569
1570     // Multiply up idx if necessary.
1571     if (!Is8Bit)
1572       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1573                                        .addReg(Idx)
1574                                        .addReg(ARM::CPSR)
1575                                        .addReg(Idx)
1576                                        .addImm(1)
1577                                        // Add predicate operands.
1578                                        .addImm(ARMCC::AL)
1579                                        .addReg(0));
1580
1581     if (Base == ARM::PC) {
1582       // TBB [base, idx] =
1583       //    ADDS idx, idx, base
1584       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1585       //    LSLS idx, #1
1586       //    ADDS pc, pc, idx
1587
1588       // When using PC as the base, it's important that there is no padding
1589       // between the last ADDS and the start of the jump table. The jump table
1590       // is 4-byte aligned, so we ensure we're 4 byte aligned here too.
1591       //
1592       // FIXME: Ideally we could vary the LDRB index based on the padding
1593       // between the sequence and jump table, however that relies on MCExprs
1594       // for load indexes which are currently not supported.
1595       OutStreamer->EmitCodeAlignment(4);
1596       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1597                                        .addReg(Idx)
1598                                        .addReg(Idx)
1599                                        .addReg(Base)
1600                                        // Add predicate operands.
1601                                        .addImm(ARMCC::AL)
1602                                        .addReg(0));
1603
1604       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1605       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1606                                        .addReg(Idx)
1607                                        .addReg(Idx)
1608                                        .addImm(Is8Bit ? 4 : 2)
1609                                        // Add predicate operands.
1610                                        .addImm(ARMCC::AL)
1611                                        .addReg(0));
1612     } else {
1613       // TBB [base, idx] =
1614       //    LDRB idx, [base, idx] ; or LDRH if TBH
1615       //    LSLS idx, #1
1616       //    ADDS pc, pc, idx
1617
1618       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1619       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1620                                        .addReg(Idx)
1621                                        .addReg(Base)
1622                                        .addReg(Idx)
1623                                        // Add predicate operands.
1624                                        .addImm(ARMCC::AL)
1625                                        .addReg(0));
1626     }
1627
1628     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1629                                      .addReg(Idx)
1630                                      .addReg(ARM::CPSR)
1631                                      .addReg(Idx)
1632                                      .addImm(1)
1633                                      // Add predicate operands.
1634                                      .addImm(ARMCC::AL)
1635                                      .addReg(0));
1636
1637     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1638     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1639                                      .addReg(ARM::PC)
1640                                      .addReg(ARM::PC)
1641                                      .addReg(Idx)
1642                                      // Add predicate operands.
1643                                      .addImm(ARMCC::AL)
1644                                      .addReg(0));
1645     return;
1646   }
1647   case ARM::tBR_JTr:
1648   case ARM::BR_JTr: {
1649     // mov pc, target
1650     MCInst TmpInst;
1651     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1652       ARM::MOVr : ARM::tMOVr;
1653     TmpInst.setOpcode(Opc);
1654     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1655     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1656     // Add predicate operands.
1657     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1658     TmpInst.addOperand(MCOperand::createReg(0));
1659     // Add 's' bit operand (always reg0 for this)
1660     if (Opc == ARM::MOVr)
1661       TmpInst.addOperand(MCOperand::createReg(0));
1662     EmitToStreamer(*OutStreamer, TmpInst);
1663     return;
1664   }
1665   case ARM::BR_JTm_i12: {
1666     // ldr pc, target
1667     MCInst TmpInst;
1668     TmpInst.setOpcode(ARM::LDRi12);
1669     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1670     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1671     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1672     // Add predicate operands.
1673     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1674     TmpInst.addOperand(MCOperand::createReg(0));
1675     EmitToStreamer(*OutStreamer, TmpInst);
1676     return;
1677   }
1678   case ARM::BR_JTm_rs: {
1679     // ldr pc, target
1680     MCInst TmpInst;
1681     TmpInst.setOpcode(ARM::LDRrs);
1682     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1683     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1684     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1685     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1686     // Add predicate operands.
1687     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1688     TmpInst.addOperand(MCOperand::createReg(0));
1689     EmitToStreamer(*OutStreamer, TmpInst);
1690     return;
1691   }
1692   case ARM::BR_JTadd: {
1693     // add pc, target, idx
1694     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1695       .addReg(ARM::PC)
1696       .addReg(MI->getOperand(0).getReg())
1697       .addReg(MI->getOperand(1).getReg())
1698       // Add predicate operands.
1699       .addImm(ARMCC::AL)
1700       .addReg(0)
1701       // Add 's' bit operand (always reg0 for this)
1702       .addReg(0));
1703     return;
1704   }
1705   case ARM::SPACE:
1706     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1707     return;
1708   case ARM::TRAP: {
1709     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1710     // FIXME: Remove this special case when they do.
1711     if (!Subtarget->isTargetMachO()) {
1712       uint32_t Val = 0xe7ffdefeUL;
1713       OutStreamer->AddComment("trap");
1714       ATS.emitInst(Val);
1715       return;
1716     }
1717     break;
1718   }
1719   case ARM::TRAPNaCl: {
1720     uint32_t Val = 0xe7fedef0UL;
1721     OutStreamer->AddComment("trap");
1722     ATS.emitInst(Val);
1723     return;
1724   }
1725   case ARM::tTRAP: {
1726     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1727     // FIXME: Remove this special case when they do.
1728     if (!Subtarget->isTargetMachO()) {
1729       uint16_t Val = 0xdefe;
1730       OutStreamer->AddComment("trap");
1731       ATS.emitInst(Val, 'n');
1732       return;
1733     }
1734     break;
1735   }
1736   case ARM::t2Int_eh_sjlj_setjmp:
1737   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1738   case ARM::tInt_eh_sjlj_setjmp: {
1739     // Two incoming args: GPR:$src, GPR:$val
1740     // mov $val, pc
1741     // adds $val, #7
1742     // str $val, [$src, #4]
1743     // movs r0, #0
1744     // b LSJLJEH
1745     // movs r0, #1
1746     // LSJLJEH:
1747     unsigned SrcReg = MI->getOperand(0).getReg();
1748     unsigned ValReg = MI->getOperand(1).getReg();
1749     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1750     OutStreamer->AddComment("eh_setjmp begin");
1751     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1752       .addReg(ValReg)
1753       .addReg(ARM::PC)
1754       // Predicate.
1755       .addImm(ARMCC::AL)
1756       .addReg(0));
1757
1758     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1759       .addReg(ValReg)
1760       // 's' bit operand
1761       .addReg(ARM::CPSR)
1762       .addReg(ValReg)
1763       .addImm(7)
1764       // Predicate.
1765       .addImm(ARMCC::AL)
1766       .addReg(0));
1767
1768     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1769       .addReg(ValReg)
1770       .addReg(SrcReg)
1771       // The offset immediate is #4. The operand value is scaled by 4 for the
1772       // tSTR instruction.
1773       .addImm(1)
1774       // Predicate.
1775       .addImm(ARMCC::AL)
1776       .addReg(0));
1777
1778     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1779       .addReg(ARM::R0)
1780       .addReg(ARM::CPSR)
1781       .addImm(0)
1782       // Predicate.
1783       .addImm(ARMCC::AL)
1784       .addReg(0));
1785
1786     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1787     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1788       .addExpr(SymbolExpr)
1789       .addImm(ARMCC::AL)
1790       .addReg(0));
1791
1792     OutStreamer->AddComment("eh_setjmp end");
1793     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1794       .addReg(ARM::R0)
1795       .addReg(ARM::CPSR)
1796       .addImm(1)
1797       // Predicate.
1798       .addImm(ARMCC::AL)
1799       .addReg(0));
1800
1801     OutStreamer->EmitLabel(Label);
1802     return;
1803   }
1804
1805   case ARM::Int_eh_sjlj_setjmp_nofp:
1806   case ARM::Int_eh_sjlj_setjmp: {
1807     // Two incoming args: GPR:$src, GPR:$val
1808     // add $val, pc, #8
1809     // str $val, [$src, #+4]
1810     // mov r0, #0
1811     // add pc, pc, #0
1812     // mov r0, #1
1813     unsigned SrcReg = MI->getOperand(0).getReg();
1814     unsigned ValReg = MI->getOperand(1).getReg();
1815
1816     OutStreamer->AddComment("eh_setjmp begin");
1817     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1818       .addReg(ValReg)
1819       .addReg(ARM::PC)
1820       .addImm(8)
1821       // Predicate.
1822       .addImm(ARMCC::AL)
1823       .addReg(0)
1824       // 's' bit operand (always reg0 for this).
1825       .addReg(0));
1826
1827     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1828       .addReg(ValReg)
1829       .addReg(SrcReg)
1830       .addImm(4)
1831       // Predicate.
1832       .addImm(ARMCC::AL)
1833       .addReg(0));
1834
1835     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1836       .addReg(ARM::R0)
1837       .addImm(0)
1838       // Predicate.
1839       .addImm(ARMCC::AL)
1840       .addReg(0)
1841       // 's' bit operand (always reg0 for this).
1842       .addReg(0));
1843
1844     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1845       .addReg(ARM::PC)
1846       .addReg(ARM::PC)
1847       .addImm(0)
1848       // Predicate.
1849       .addImm(ARMCC::AL)
1850       .addReg(0)
1851       // 's' bit operand (always reg0 for this).
1852       .addReg(0));
1853
1854     OutStreamer->AddComment("eh_setjmp end");
1855     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1856       .addReg(ARM::R0)
1857       .addImm(1)
1858       // Predicate.
1859       .addImm(ARMCC::AL)
1860       .addReg(0)
1861       // 's' bit operand (always reg0 for this).
1862       .addReg(0));
1863     return;
1864   }
1865   case ARM::Int_eh_sjlj_longjmp: {
1866     // ldr sp, [$src, #8]
1867     // ldr $scratch, [$src, #4]
1868     // ldr r7, [$src]
1869     // bx $scratch
1870     unsigned SrcReg = MI->getOperand(0).getReg();
1871     unsigned ScratchReg = MI->getOperand(1).getReg();
1872     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1873       .addReg(ARM::SP)
1874       .addReg(SrcReg)
1875       .addImm(8)
1876       // Predicate.
1877       .addImm(ARMCC::AL)
1878       .addReg(0));
1879
1880     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1881       .addReg(ScratchReg)
1882       .addReg(SrcReg)
1883       .addImm(4)
1884       // Predicate.
1885       .addImm(ARMCC::AL)
1886       .addReg(0));
1887
1888     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
1889       // These platforms always use the same frame register
1890       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1891         .addReg(FramePtr)
1892         .addReg(SrcReg)
1893         .addImm(0)
1894         // Predicate.
1895         .addImm(ARMCC::AL)
1896         .addReg(0));
1897     } else {
1898       // If the calling code might use either R7 or R11 as
1899       // frame pointer register, restore it into both.
1900       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1901         .addReg(ARM::R7)
1902         .addReg(SrcReg)
1903         .addImm(0)
1904         // Predicate.
1905         .addImm(ARMCC::AL)
1906         .addReg(0));
1907       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1908         .addReg(ARM::R11)
1909         .addReg(SrcReg)
1910         .addImm(0)
1911         // Predicate.
1912         .addImm(ARMCC::AL)
1913         .addReg(0));
1914     }
1915
1916     assert(Subtarget->hasV4TOps());
1917     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1918       .addReg(ScratchReg)
1919       // Predicate.
1920       .addImm(ARMCC::AL)
1921       .addReg(0));
1922     return;
1923   }
1924   case ARM::tInt_eh_sjlj_longjmp: {
1925     // ldr $scratch, [$src, #8]
1926     // mov sp, $scratch
1927     // ldr $scratch, [$src, #4]
1928     // ldr r7, [$src]
1929     // bx $scratch
1930     unsigned SrcReg = MI->getOperand(0).getReg();
1931     unsigned ScratchReg = MI->getOperand(1).getReg();
1932
1933     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1934       .addReg(ScratchReg)
1935       .addReg(SrcReg)
1936       // The offset immediate is #8. The operand value is scaled by 4 for the
1937       // tLDR instruction.
1938       .addImm(2)
1939       // Predicate.
1940       .addImm(ARMCC::AL)
1941       .addReg(0));
1942
1943     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1944       .addReg(ARM::SP)
1945       .addReg(ScratchReg)
1946       // Predicate.
1947       .addImm(ARMCC::AL)
1948       .addReg(0));
1949
1950     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1951       .addReg(ScratchReg)
1952       .addReg(SrcReg)
1953       .addImm(1)
1954       // Predicate.
1955       .addImm(ARMCC::AL)
1956       .addReg(0));
1957
1958     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
1959       // These platforms always use the same frame register
1960       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1961         .addReg(FramePtr)
1962         .addReg(SrcReg)
1963         .addImm(0)
1964         // Predicate.
1965         .addImm(ARMCC::AL)
1966         .addReg(0));
1967     } else {
1968       // If the calling code might use either R7 or R11 as
1969       // frame pointer register, restore it into both.
1970       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1971         .addReg(ARM::R7)
1972         .addReg(SrcReg)
1973         .addImm(0)
1974         // Predicate.
1975         .addImm(ARMCC::AL)
1976         .addReg(0));
1977       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1978         .addReg(ARM::R11)
1979         .addReg(SrcReg)
1980         .addImm(0)
1981         // Predicate.
1982         .addImm(ARMCC::AL)
1983         .addReg(0));
1984     }
1985
1986     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
1987       .addReg(ScratchReg)
1988       // Predicate.
1989       .addImm(ARMCC::AL)
1990       .addReg(0));
1991     return;
1992   }
1993   case ARM::tInt_WIN_eh_sjlj_longjmp: {
1994     // ldr.w r11, [$src, #0]
1995     // ldr.w  sp, [$src, #8]
1996     // ldr.w  pc, [$src, #4]
1997
1998     unsigned SrcReg = MI->getOperand(0).getReg();
1999
2000     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2001                                      .addReg(ARM::R11)
2002                                      .addReg(SrcReg)
2003                                      .addImm(0)
2004                                      // Predicate
2005                                      .addImm(ARMCC::AL)
2006                                      .addReg(0));
2007     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2008                                      .addReg(ARM::SP)
2009                                      .addReg(SrcReg)
2010                                      .addImm(8)
2011                                      // Predicate
2012                                      .addImm(ARMCC::AL)
2013                                      .addReg(0));
2014     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2015                                      .addReg(ARM::PC)
2016                                      .addReg(SrcReg)
2017                                      .addImm(4)
2018                                      // Predicate
2019                                      .addImm(ARMCC::AL)
2020                                      .addReg(0));
2021     return;
2022   }
2023   case ARM::PATCHABLE_FUNCTION_ENTER:
2024     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2025     return;
2026   case ARM::PATCHABLE_FUNCTION_EXIT:
2027     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2028     return;
2029   case ARM::PATCHABLE_TAIL_CALL:
2030     LowerPATCHABLE_TAIL_CALL(*MI);
2031     return;
2032   }
2033
2034   MCInst TmpInst;
2035   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2036
2037   EmitToStreamer(*OutStreamer, TmpInst);
2038 }
2039
2040 //===----------------------------------------------------------------------===//
2041 // Target Registry Stuff
2042 //===----------------------------------------------------------------------===//
2043
2044 // Force static initialization.
2045 extern "C" void LLVMInitializeARMAsmPrinter() {
2046   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2047   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2048   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2049   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2050 }