Remove the TargetMachine forwards for TargetSubtargetInfo based
[oota-llvm.git] / 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 "ARMFPUName.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMTargetMachine.h"
21 #include "ARMTargetObjectFile.h"
22 #include "InstPrinter/ARMInstPrinter.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "MCTargetDesc/ARMMCExpr.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallString.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/DebugInfo.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCAssembler.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCELFStreamer.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCInstBuilder.h"
42 #include "llvm/MC/MCObjectStreamer.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/ARMBuildAttributes.h"
47 #include "llvm/Support/COFF.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ELF.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "asm-printer"
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   }
74
75   OutStreamer.EmitLabel(CurrentFnSym);
76 }
77
78 void ARMAsmPrinter::EmitXXStructor(const Constant *CV) {
79   uint64_t Size =
80       TM.getSubtargetImpl()->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 /// runOnMachineFunction - This uses the EmitInstruction()
97 /// method to print assembly for each instruction.
98 ///
99 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
100   AFI = MF.getInfo<ARMFunctionInfo>();
101   MCP = MF.getConstantPool();
102
103   SetupMachineFunction(MF);
104
105   if (Subtarget->isTargetCOFF()) {
106     bool Internal = MF.getFunction()->hasInternalLinkage();
107     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
108                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
109     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
110
111     OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
112     OutStreamer.EmitCOFFSymbolStorageClass(Scl);
113     OutStreamer.EmitCOFFSymbolType(Type);
114     OutStreamer.EndCOFFSymbolDef();
115   }
116
117   // Have common code print out the function header with linkage info etc.
118   EmitFunctionHeader();
119
120   // Emit the rest of the function body.
121   EmitFunctionBody();
122
123   // We didn't modify anything.
124   return false;
125 }
126
127 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
128                                  raw_ostream &O, const char *Modifier) {
129   const MachineOperand &MO = MI->getOperand(OpNum);
130   unsigned TF = MO.getTargetFlags();
131
132   switch (MO.getType()) {
133   default: llvm_unreachable("<unknown operand type>");
134   case MachineOperand::MO_Register: {
135     unsigned Reg = MO.getReg();
136     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
137     assert(!MO.getSubReg() && "Subregs should be eliminated!");
138     if(ARM::GPRPairRegClass.contains(Reg)) {
139       const MachineFunction &MF = *MI->getParent()->getParent();
140       const TargetRegisterInfo *TRI =
141           MF.getTarget().getSubtargetImpl()->getRegisterInfo();
142       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
143     }
144     O << ARMInstPrinter::getRegisterName(Reg);
145     break;
146   }
147   case MachineOperand::MO_Immediate: {
148     int64_t Imm = MO.getImm();
149     O << '#';
150     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
151         (TF == ARMII::MO_LO16))
152       O << ":lower16:";
153     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
154              (TF == ARMII::MO_HI16))
155       O << ":upper16:";
156     O << Imm;
157     break;
158   }
159   case MachineOperand::MO_MachineBasicBlock:
160     O << *MO.getMBB()->getSymbol();
161     return;
162   case MachineOperand::MO_GlobalAddress: {
163     const GlobalValue *GV = MO.getGlobal();
164     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
165         (TF & ARMII::MO_LO16))
166       O << ":lower16:";
167     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
168              (TF & ARMII::MO_HI16))
169       O << ":upper16:";
170     O << *GetARMGVSymbol(GV, TF);
171
172     printOffset(MO.getOffset(), O);
173     if (TF == ARMII::MO_PLT)
174       O << "(PLT)";
175     break;
176   }
177   case MachineOperand::MO_ConstantPoolIndex:
178     O << *GetCPISymbol(MO.getIndex());
179     break;
180   }
181 }
182
183 //===--------------------------------------------------------------------===//
184
185 MCSymbol *ARMAsmPrinter::
186 GetARMJTIPICJumpTableLabel2(unsigned uid, unsigned uid2) const {
187   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
188   SmallString<60> Name;
189   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "JTI"
190     << getFunctionNumber() << '_' << uid << '_' << uid2;
191   return OutContext.GetOrCreateSymbol(Name.str());
192 }
193
194
195 MCSymbol *ARMAsmPrinter::GetARMSJLJEHLabel() const {
196   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
197   SmallString<60> Name;
198   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "SJLJEH"
199     << getFunctionNumber();
200   return OutContext.GetOrCreateSymbol(Name.str());
201 }
202
203 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
204                                     unsigned AsmVariant, const char *ExtraCode,
205                                     raw_ostream &O) {
206   // Does this asm operand have a single letter operand modifier?
207   if (ExtraCode && ExtraCode[0]) {
208     if (ExtraCode[1] != 0) return true; // Unknown modifier.
209
210     switch (ExtraCode[0]) {
211     default:
212       // See if this is a generic print operand
213       return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
214     case 'a': // Print as a memory address.
215       if (MI->getOperand(OpNum).isReg()) {
216         O << "["
217           << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
218           << "]";
219         return false;
220       }
221       // Fallthrough
222     case 'c': // Don't print "#" before an immediate operand.
223       if (!MI->getOperand(OpNum).isImm())
224         return true;
225       O << MI->getOperand(OpNum).getImm();
226       return false;
227     case 'P': // Print a VFP double precision register.
228     case 'q': // Print a NEON quad precision register.
229       printOperand(MI, OpNum, O);
230       return false;
231     case 'y': // Print a VFP single precision register as indexed double.
232       if (MI->getOperand(OpNum).isReg()) {
233         unsigned Reg = MI->getOperand(OpNum).getReg();
234         const TargetRegisterInfo *TRI =
235             MF->getTarget().getSubtargetImpl()->getRegisterInfo();
236         // Find the 'd' register that has this 's' register as a sub-register,
237         // and determine the lane number.
238         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
239           if (!ARM::DPRRegClass.contains(*SR))
240             continue;
241           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
242           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
243           return false;
244         }
245       }
246       return true;
247     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
248       if (!MI->getOperand(OpNum).isImm())
249         return true;
250       O << ~(MI->getOperand(OpNum).getImm());
251       return false;
252     case 'L': // The low 16 bits of an immediate constant.
253       if (!MI->getOperand(OpNum).isImm())
254         return true;
255       O << (MI->getOperand(OpNum).getImm() & 0xffff);
256       return false;
257     case 'M': { // A register range suitable for LDM/STM.
258       if (!MI->getOperand(OpNum).isReg())
259         return true;
260       const MachineOperand &MO = MI->getOperand(OpNum);
261       unsigned RegBegin = MO.getReg();
262       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
263       // already got the operands in registers that are operands to the
264       // inline asm statement.
265       O << "{";
266       if (ARM::GPRPairRegClass.contains(RegBegin)) {
267         const TargetRegisterInfo *TRI =
268             MF->getTarget().getSubtargetImpl()->getRegisterInfo();
269         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
270         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
271         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
272       }
273       O << ARMInstPrinter::getRegisterName(RegBegin);
274
275       // FIXME: The register allocator not only may not have given us the
276       // registers in sequence, but may not be in ascending registers. This
277       // will require changes in the register allocator that'll need to be
278       // propagated down here if the operands change.
279       unsigned RegOps = OpNum + 1;
280       while (MI->getOperand(RegOps).isReg()) {
281         O << ", "
282           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
283         RegOps++;
284       }
285
286       O << "}";
287
288       return false;
289     }
290     case 'R': // The most significant register of a pair.
291     case 'Q': { // The least significant register of a pair.
292       if (OpNum == 0)
293         return true;
294       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
295       if (!FlagsOP.isImm())
296         return true;
297       unsigned Flags = FlagsOP.getImm();
298
299       // This operand may not be the one that actually provides the register. If
300       // it's tied to a previous one then we should refer instead to that one
301       // for registers and their classes.
302       unsigned TiedIdx;
303       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
304         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
305           unsigned OpFlags = MI->getOperand(OpNum).getImm();
306           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
307         }
308         Flags = MI->getOperand(OpNum).getImm();
309
310         // Later code expects OpNum to be pointing at the register rather than
311         // the flags.
312         OpNum += 1;
313       }
314
315       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
316       unsigned RC;
317       InlineAsm::hasRegClassConstraint(Flags, RC);
318       if (RC == ARM::GPRPairRegClassID) {
319         if (NumVals != 1)
320           return true;
321         const MachineOperand &MO = MI->getOperand(OpNum);
322         if (!MO.isReg())
323           return true;
324         const TargetRegisterInfo *TRI =
325             MF->getTarget().getSubtargetImpl()->getRegisterInfo();
326         unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
327             ARM::gsub_0 : ARM::gsub_1);
328         O << ARMInstPrinter::getRegisterName(Reg);
329         return false;
330       }
331       if (NumVals != 2)
332         return true;
333       unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
334       if (RegOp >= MI->getNumOperands())
335         return true;
336       const MachineOperand &MO = MI->getOperand(RegOp);
337       if (!MO.isReg())
338         return true;
339       unsigned Reg = MO.getReg();
340       O << ARMInstPrinter::getRegisterName(Reg);
341       return false;
342     }
343
344     case 'e': // The low doubleword register of a NEON quad register.
345     case 'f': { // The high doubleword register of a NEON quad register.
346       if (!MI->getOperand(OpNum).isReg())
347         return true;
348       unsigned Reg = MI->getOperand(OpNum).getReg();
349       if (!ARM::QPRRegClass.contains(Reg))
350         return true;
351       const TargetRegisterInfo *TRI =
352           MF->getTarget().getSubtargetImpl()->getRegisterInfo();
353       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
354                                        ARM::dsub_0 : ARM::dsub_1);
355       O << ARMInstPrinter::getRegisterName(SubReg);
356       return false;
357     }
358
359     // This modifier is not yet supported.
360     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
361       return true;
362     case 'H': { // The highest-numbered register of a pair.
363       const MachineOperand &MO = MI->getOperand(OpNum);
364       if (!MO.isReg())
365         return true;
366       const MachineFunction &MF = *MI->getParent()->getParent();
367       const TargetRegisterInfo *TRI =
368           MF.getTarget().getSubtargetImpl()->getRegisterInfo();
369       unsigned Reg = MO.getReg();
370       if(!ARM::GPRPairRegClass.contains(Reg))
371         return false;
372       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
373       O << ARMInstPrinter::getRegisterName(Reg);
374       return false;
375     }
376     }
377   }
378
379   printOperand(MI, OpNum, O);
380   return false;
381 }
382
383 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
384                                           unsigned OpNum, unsigned AsmVariant,
385                                           const char *ExtraCode,
386                                           raw_ostream &O) {
387   // Does this asm operand have a single letter operand modifier?
388   if (ExtraCode && ExtraCode[0]) {
389     if (ExtraCode[1] != 0) return true; // Unknown modifier.
390
391     switch (ExtraCode[0]) {
392       case 'A': // A memory operand for a VLD1/VST1 instruction.
393       default: return true;  // Unknown modifier.
394       case 'm': // The base register of a memory operand.
395         if (!MI->getOperand(OpNum).isReg())
396           return true;
397         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
398         return false;
399     }
400   }
401
402   const MachineOperand &MO = MI->getOperand(OpNum);
403   assert(MO.isReg() && "unexpected inline asm memory operand");
404   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
405   return false;
406 }
407
408 static bool isThumb(const MCSubtargetInfo& STI) {
409   return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
410 }
411
412 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
413                                      const MCSubtargetInfo *EndInfo) const {
414   // If either end mode is unknown (EndInfo == NULL) or different than
415   // the start mode, then restore the start mode.
416   const bool WasThumb = isThumb(StartInfo);
417   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
418     OutStreamer.EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
419   }
420 }
421
422 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
423   if (Subtarget->isTargetMachO()) {
424     Reloc::Model RelocM = TM.getRelocationModel();
425     if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
426       // Declare all the text sections up front (before the DWARF sections
427       // emitted by AsmPrinter::doInitialization) so the assembler will keep
428       // them together at the beginning of the object file.  This helps
429       // avoid out-of-range branches that are due a fundamental limitation of
430       // the way symbol offsets are encoded with the current Darwin ARM
431       // relocations.
432       const TargetLoweringObjectFileMachO &TLOFMacho =
433         static_cast<const TargetLoweringObjectFileMachO &>(
434           getObjFileLowering());
435
436       // Collect the set of sections our functions will go into.
437       SetVector<const MCSection *, SmallVector<const MCSection *, 8>,
438         SmallPtrSet<const MCSection *, 8> > TextSections;
439       // Default text section comes first.
440       TextSections.insert(TLOFMacho.getTextSection());
441       // Now any user defined text sections from function attributes.
442       for (Module::iterator F = M.begin(), e = M.end(); F != e; ++F)
443         if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage())
444           TextSections.insert(TLOFMacho.SectionForGlobal(F, *Mang, TM));
445       // Now the coalescable sections.
446       TextSections.insert(TLOFMacho.getTextCoalSection());
447       TextSections.insert(TLOFMacho.getConstTextCoalSection());
448
449       // Emit the sections in the .s file header to fix the order.
450       for (unsigned i = 0, e = TextSections.size(); i != e; ++i)
451         OutStreamer.SwitchSection(TextSections[i]);
452
453       if (RelocM == Reloc::DynamicNoPIC) {
454         const MCSection *sect =
455           OutContext.getMachOSection("__TEXT", "__symbol_stub4",
456                                      MachO::S_SYMBOL_STUBS,
457                                      12, SectionKind::getText());
458         OutStreamer.SwitchSection(sect);
459       } else {
460         const MCSection *sect =
461           OutContext.getMachOSection("__TEXT", "__picsymbolstub4",
462                                      MachO::S_SYMBOL_STUBS,
463                                      16, SectionKind::getText());
464         OutStreamer.SwitchSection(sect);
465       }
466       const MCSection *StaticInitSect =
467         OutContext.getMachOSection("__TEXT", "__StaticInit",
468                                    MachO::S_REGULAR |
469                                    MachO::S_ATTR_PURE_INSTRUCTIONS,
470                                    SectionKind::getText());
471       OutStreamer.SwitchSection(StaticInitSect);
472     }
473
474     // Compiling with debug info should not affect the code
475     // generation.  Ensure the cstring section comes before the
476     // optional __DWARF secion. Otherwise, PC-relative loads would
477     // have to use different instruction sequences at "-g" in order to
478     // reach global data in the same object file.
479     OutStreamer.SwitchSection(getObjFileLowering().getCStringSection());
480   }
481
482   // Use unified assembler syntax.
483   OutStreamer.EmitAssemblerFlag(MCAF_SyntaxUnified);
484
485   // Emit ARM Build Attributes
486   if (Subtarget->isTargetELF())
487     emitAttributes();
488
489   if (!M.getModuleInlineAsm().empty() && Subtarget->isThumb())
490     OutStreamer.EmitAssemblerFlag(MCAF_Code16);
491 }
492
493 static void
494 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
495                          MachineModuleInfoImpl::StubValueTy &MCSym) {
496   // L_foo$stub:
497   OutStreamer.EmitLabel(StubLabel);
498   //   .indirect_symbol _foo
499   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
500
501   if (MCSym.getInt())
502     // External to current translation unit.
503     OutStreamer.EmitIntValue(0, 4/*size*/);
504   else
505     // Internal to current translation unit.
506     //
507     // When we place the LSDA into the TEXT section, the type info
508     // pointers need to be indirect and pc-rel. We accomplish this by
509     // using NLPs; however, sometimes the types are local to the file.
510     // We need to fill in the value for the NLP in those cases.
511     OutStreamer.EmitValue(
512         MCSymbolRefExpr::Create(MCSym.getPointer(), OutStreamer.getContext()),
513         4 /*size*/);
514 }
515
516
517 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
518   if (Subtarget->isTargetMachO()) {
519     // All darwin targets use mach-o.
520     const TargetLoweringObjectFileMachO &TLOFMacho =
521       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
522     MachineModuleInfoMachO &MMIMacho =
523       MMI->getObjFileInfo<MachineModuleInfoMachO>();
524
525     // Output non-lazy-pointers for external and common global variables.
526     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
527
528     if (!Stubs.empty()) {
529       // Switch with ".non_lazy_symbol_pointer" directive.
530       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
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     Stubs = MMIMacho.GetHiddenGVStubList();
541     if (!Stubs.empty()) {
542       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
543       EmitAlignment(2);
544
545       for (auto &Stub : Stubs)
546         emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
547
548       Stubs.clear();
549       OutStreamer.AddBlankLine();
550     }
551
552     // Funny Darwin hack: This flag tells the linker that no global symbols
553     // contain code that falls through to other global symbols (e.g. the obvious
554     // implementation of multiple entry points).  If this doesn't occur, the
555     // linker can safely perform dead code stripping.  Since LLVM never
556     // generates code that does this, it is always safe to set.
557     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
558   }
559
560   // Emit a .data.rel section containing any stubs that were created.
561   if (Subtarget->isTargetELF()) {
562     const TargetLoweringObjectFileELF &TLOFELF =
563       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
564
565     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
566
567     // Output stubs for external and common global variables.
568     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
569     if (!Stubs.empty()) {
570       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
571       const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
572
573       for (auto &stub: Stubs) {
574         OutStreamer.EmitLabel(stub.first);
575         OutStreamer.EmitSymbolValue(stub.second.getPointer(),
576                                     TD->getPointerSize(0));
577       }
578       Stubs.clear();
579     }
580   }
581 }
582
583 //===----------------------------------------------------------------------===//
584 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
585 // FIXME:
586 // The following seem like one-off assembler flags, but they actually need
587 // to appear in the .ARM.attributes section in ELF.
588 // Instead of subclassing the MCELFStreamer, we do the work here.
589
590 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
591                                             const ARMSubtarget *Subtarget) {
592   if (CPU == "xscale")
593     return ARMBuildAttrs::v5TEJ;
594
595   if (Subtarget->hasV8Ops())
596     return ARMBuildAttrs::v8;
597   else if (Subtarget->hasV7Ops()) {
598     if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
599       return ARMBuildAttrs::v7E_M;
600     return ARMBuildAttrs::v7;
601   } else if (Subtarget->hasV6T2Ops())
602     return ARMBuildAttrs::v6T2;
603   else if (Subtarget->hasV6MOps())
604     return ARMBuildAttrs::v6S_M;
605   else if (Subtarget->hasV6Ops())
606     return ARMBuildAttrs::v6;
607   else if (Subtarget->hasV5TEOps())
608     return ARMBuildAttrs::v5TE;
609   else if (Subtarget->hasV5TOps())
610     return ARMBuildAttrs::v5T;
611   else if (Subtarget->hasV4TOps())
612     return ARMBuildAttrs::v4T;
613   else
614     return ARMBuildAttrs::v4;
615 }
616
617 void ARMAsmPrinter::emitAttributes() {
618   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
619   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
620
621   ATS.switchVendor("aeabi");
622
623   std::string CPUString = Subtarget->getCPUString();
624
625   // FIXME: remove krait check when GNU tools support krait cpu
626   if (CPUString != "generic" && CPUString != "krait")
627     ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
628
629   ATS.emitAttribute(ARMBuildAttrs::CPU_arch,
630                     getArchForCPU(CPUString, Subtarget));
631
632   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
633   // profile is not applicable (e.g. pre v7, or cross-profile code)".
634   if (Subtarget->hasV7Ops()) {
635     if (Subtarget->isAClass()) {
636       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
637                         ARMBuildAttrs::ApplicationProfile);
638     } else if (Subtarget->isRClass()) {
639       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
640                         ARMBuildAttrs::RealTimeProfile);
641     } else if (Subtarget->isMClass()) {
642       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
643                         ARMBuildAttrs::MicroControllerProfile);
644     }
645   }
646
647   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use, Subtarget->hasARMOps() ?
648                       ARMBuildAttrs::Allowed : ARMBuildAttrs::Not_Allowed);
649   if (Subtarget->isThumb1Only()) {
650     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
651                       ARMBuildAttrs::Allowed);
652   } else if (Subtarget->hasThumb2()) {
653     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
654                       ARMBuildAttrs::AllowThumb32);
655   }
656
657   if (Subtarget->hasNEON()) {
658     /* NEON is not exactly a VFP architecture, but GAS emit one of
659      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
660     if (Subtarget->hasFPARMv8()) {
661       if (Subtarget->hasCrypto())
662         ATS.emitFPU(ARM::CRYPTO_NEON_FP_ARMV8);
663       else
664         ATS.emitFPU(ARM::NEON_FP_ARMV8);
665     }
666     else if (Subtarget->hasVFP4())
667       ATS.emitFPU(ARM::NEON_VFPV4);
668     else
669       ATS.emitFPU(ARM::NEON);
670     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
671     if (Subtarget->hasV8Ops())
672       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
673                         ARMBuildAttrs::AllowNeonARMv8);
674   } else {
675     if (Subtarget->hasFPARMv8())
676       ATS.emitFPU(ARM::FP_ARMV8);
677     else if (Subtarget->hasVFP4())
678       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV4_D16 : ARM::VFPV4);
679     else if (Subtarget->hasVFP3())
680       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV3_D16 : ARM::VFPV3);
681     else if (Subtarget->hasVFP2())
682       ATS.emitFPU(ARM::VFPV2);
683   }
684
685   if (TM.getRelocationModel() == Reloc::PIC_) {
686     // PIC specific attributes.
687     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
688                       ARMBuildAttrs::AddressRWPCRel);
689     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
690                       ARMBuildAttrs::AddressROPCRel);
691     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
692                       ARMBuildAttrs::AddressGOT);
693   } else {
694     // Allow direct addressing of imported data for all other relocation models.
695     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
696                       ARMBuildAttrs::AddressDirect);
697   }
698
699   // Signal various FP modes.
700   if (!TM.Options.UnsafeFPMath) {
701     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal, ARMBuildAttrs::Allowed);
702     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
703                       ARMBuildAttrs::Allowed);
704   }
705
706   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
707     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
708                       ARMBuildAttrs::Allowed);
709   else
710     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
711                       ARMBuildAttrs::AllowIEE754);
712
713   // FIXME: add more flags to ARMBuildAttributes.h
714   // 8-bytes alignment stuff.
715   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
716   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
717
718   // ABI_HardFP_use attribute to indicate single precision FP.
719   if (Subtarget->isFPOnlySP())
720     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
721                       ARMBuildAttrs::HardFPSinglePrecision);
722
723   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
724   if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
725     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
726
727   // FIXME: Should we signal R9 usage?
728
729   if (Subtarget->hasFP16())
730       ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
731
732   if (Subtarget->hasMPExtension())
733       ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
734
735   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
736   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
737   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
738   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
739   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
740   // otherwise, the default value (AllowDIVIfExists) applies.
741   if (Subtarget->hasDivideInARMMode() && !Subtarget->hasV8Ops())
742       ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
743
744   if (MMI) {
745     if (const Module *SourceModule = MMI->getModule()) {
746       // ABI_PCS_wchar_t to indicate wchar_t width
747       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
748       if (auto WCharWidthValue = cast_or_null<ConstantInt>(
749               SourceModule->getModuleFlag("wchar_size"))) {
750         int WCharWidth = WCharWidthValue->getZExtValue();
751         assert((WCharWidth == 2 || WCharWidth == 4) &&
752                "wchar_t width must be 2 or 4 bytes");
753         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
754       }
755
756       // ABI_enum_size to indicate enum width
757       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
758       //        (all enums contain a value needing 32 bits to encode).
759       if (auto EnumWidthValue = cast_or_null<ConstantInt>(
760               SourceModule->getModuleFlag("min_enum_size"))) {
761         int EnumWidth = EnumWidthValue->getZExtValue();
762         assert((EnumWidth == 1 || EnumWidth == 4) &&
763                "Minimum enum width must be 1 or 4 bytes");
764         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
765         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
766       }
767     }
768   }
769
770   // TODO: We currently only support either reserving the register, or treating
771   // it as another callee-saved register, but not as SB or a TLS pointer; It
772   // would instead be nicer to push this from the frontend as metadata, as we do
773   // for the wchar and enum size tags
774   if (Subtarget->isR9Reserved())
775       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
776                         ARMBuildAttrs::R9Reserved);
777   else
778       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
779                         ARMBuildAttrs::R9IsGPR);
780
781   if (Subtarget->hasTrustZone() && Subtarget->hasVirtualization())
782       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
783                         ARMBuildAttrs::AllowTZVirtualization);
784   else if (Subtarget->hasTrustZone())
785       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
786                         ARMBuildAttrs::AllowTZ);
787   else if (Subtarget->hasVirtualization())
788       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
789                         ARMBuildAttrs::AllowVirtualization);
790
791   ATS.finishAttributeSection();
792 }
793
794 //===----------------------------------------------------------------------===//
795
796 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
797                              unsigned LabelId, MCContext &Ctx) {
798
799   MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
800                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
801   return Label;
802 }
803
804 static MCSymbolRefExpr::VariantKind
805 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
806   switch (Modifier) {
807   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
808   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
809   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
810   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
811   case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
812   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
813   }
814   llvm_unreachable("Invalid ARMCPModifier!");
815 }
816
817 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
818                                         unsigned char TargetFlags) {
819   if (Subtarget->isTargetMachO()) {
820     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
821       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
822
823     if (!IsIndirect)
824       return getSymbol(GV);
825
826     // FIXME: Remove this when Darwin transition to @GOT like syntax.
827     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
828     MachineModuleInfoMachO &MMIMachO =
829       MMI->getObjFileInfo<MachineModuleInfoMachO>();
830     MachineModuleInfoImpl::StubValueTy &StubSym =
831       GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym)
832                                 : MMIMachO.getGVStubEntry(MCSym);
833     if (!StubSym.getPointer())
834       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
835                                                    !GV->hasInternalLinkage());
836     return MCSym;
837   } else if (Subtarget->isTargetCOFF()) {
838     assert(Subtarget->isTargetWindows() &&
839            "Windows is the only supported COFF target");
840
841     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
842     if (!IsIndirect)
843       return getSymbol(GV);
844
845     SmallString<128> Name;
846     Name = "__imp_";
847     getNameWithPrefix(Name, GV);
848
849     return OutContext.GetOrCreateSymbol(Name);
850   } else if (Subtarget->isTargetELF()) {
851     return getSymbol(GV);
852   }
853   llvm_unreachable("unexpected target");
854 }
855
856 void ARMAsmPrinter::
857 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
858   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
859   int Size =
860       TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(MCPV->getType());
861
862   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
863
864   MCSymbol *MCSym;
865   if (ACPV->isLSDA()) {
866     SmallString<128> Str;
867     raw_svector_ostream OS(Str);
868     OS << DL->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
869     MCSym = OutContext.GetOrCreateSymbol(OS.str());
870   } else if (ACPV->isBlockAddress()) {
871     const BlockAddress *BA =
872       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
873     MCSym = GetBlockAddressSymbol(BA);
874   } else if (ACPV->isGlobalValue()) {
875     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
876
877     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
878     // flag the global as MO_NONLAZY.
879     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
880     MCSym = GetARMGVSymbol(GV, TF);
881   } else if (ACPV->isMachineBasicBlock()) {
882     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
883     MCSym = MBB->getSymbol();
884   } else {
885     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
886     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
887     MCSym = GetExternalSymbolSymbol(Sym);
888   }
889
890   // Create an MCSymbol for the reference.
891   const MCExpr *Expr =
892     MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
893                             OutContext);
894
895   if (ACPV->getPCAdjustment()) {
896     MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
897                                     getFunctionNumber(),
898                                     ACPV->getLabelId(),
899                                     OutContext);
900     const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
901     PCRelExpr =
902       MCBinaryExpr::CreateAdd(PCRelExpr,
903                               MCConstantExpr::Create(ACPV->getPCAdjustment(),
904                                                      OutContext),
905                               OutContext);
906     if (ACPV->mustAddCurrentAddress()) {
907       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
908       // label, so just emit a local label end reference that instead.
909       MCSymbol *DotSym = OutContext.CreateTempSymbol();
910       OutStreamer.EmitLabel(DotSym);
911       const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
912       PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
913     }
914     Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
915   }
916   OutStreamer.EmitValue(Expr, Size);
917 }
918
919 void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
920   unsigned Opcode = MI->getOpcode();
921   int OpNum = 1;
922   if (Opcode == ARM::BR_JTadd)
923     OpNum = 2;
924   else if (Opcode == ARM::BR_JTm)
925     OpNum = 3;
926
927   const MachineOperand &MO1 = MI->getOperand(OpNum);
928   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
929   unsigned JTI = MO1.getIndex();
930
931   // Emit a label for the jump table.
932   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
933   OutStreamer.EmitLabel(JTISymbol);
934
935   // Mark the jump table as data-in-code.
936   OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
937
938   // Emit each entry of the table.
939   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
940   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
941   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
942
943   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
944     MachineBasicBlock *MBB = JTBBs[i];
945     // Construct an MCExpr for the entry. We want a value of the form:
946     // (BasicBlockAddr - TableBeginAddr)
947     //
948     // For example, a table with entries jumping to basic blocks BB0 and BB1
949     // would look like:
950     // LJTI_0_0:
951     //    .word (LBB0 - LJTI_0_0)
952     //    .word (LBB1 - LJTI_0_0)
953     const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
954
955     if (TM.getRelocationModel() == Reloc::PIC_)
956       Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
957                                                                    OutContext),
958                                      OutContext);
959     // If we're generating a table of Thumb addresses in static relocation
960     // model, we need to add one to keep interworking correctly.
961     else if (AFI->isThumbFunction())
962       Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
963                                      OutContext);
964     OutStreamer.EmitValue(Expr, 4);
965   }
966   // Mark the end of jump table data-in-code region.
967   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
968 }
969
970 void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
971   unsigned Opcode = MI->getOpcode();
972   int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
973   const MachineOperand &MO1 = MI->getOperand(OpNum);
974   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
975   unsigned JTI = MO1.getIndex();
976
977   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
978   OutStreamer.EmitLabel(JTISymbol);
979
980   // Emit each entry of the table.
981   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
982   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
983   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
984   unsigned OffsetWidth = 4;
985   if (MI->getOpcode() == ARM::t2TBB_JT) {
986     OffsetWidth = 1;
987     // Mark the jump table as data-in-code.
988     OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
989   } else if (MI->getOpcode() == ARM::t2TBH_JT) {
990     OffsetWidth = 2;
991     // Mark the jump table as data-in-code.
992     OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
993   }
994
995   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
996     MachineBasicBlock *MBB = JTBBs[i];
997     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
998                                                           OutContext);
999     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1000     if (OffsetWidth == 4) {
1001       EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2B)
1002         .addExpr(MBBSymbolExpr)
1003         .addImm(ARMCC::AL)
1004         .addReg(0));
1005       continue;
1006     }
1007     // Otherwise it's an offset from the dispatch instruction. Construct an
1008     // MCExpr for the entry. We want a value of the form:
1009     // (BasicBlockAddr - TableBeginAddr) / 2
1010     //
1011     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1012     // would look like:
1013     // LJTI_0_0:
1014     //    .byte (LBB0 - LJTI_0_0) / 2
1015     //    .byte (LBB1 - LJTI_0_0) / 2
1016     const MCExpr *Expr =
1017       MCBinaryExpr::CreateSub(MBBSymbolExpr,
1018                               MCSymbolRefExpr::Create(JTISymbol, OutContext),
1019                               OutContext);
1020     Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
1021                                    OutContext);
1022     OutStreamer.EmitValue(Expr, OffsetWidth);
1023   }
1024   // Mark the end of jump table data-in-code region. 32-bit offsets use
1025   // actual branch instructions here, so we don't mark those as a data-region
1026   // at all.
1027   if (OffsetWidth != 4)
1028     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1029 }
1030
1031 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1032   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1033       "Only instruction which are involved into frame setup code are allowed");
1034
1035   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
1036   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1037   const MachineFunction &MF = *MI->getParent()->getParent();
1038   const TargetRegisterInfo *RegInfo =
1039       MF.getTarget().getSubtargetImpl()->getRegisterInfo();
1040   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1041
1042   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1043   unsigned Opc = MI->getOpcode();
1044   unsigned SrcReg, DstReg;
1045
1046   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1047     // Two special cases:
1048     // 1) tPUSH does not have src/dst regs.
1049     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1050     // load. Yes, this is pretty fragile, but for now I don't see better
1051     // way... :(
1052     SrcReg = DstReg = ARM::SP;
1053   } else {
1054     SrcReg = MI->getOperand(1).getReg();
1055     DstReg = MI->getOperand(0).getReg();
1056   }
1057
1058   // Try to figure out the unwinding opcode out of src / dst regs.
1059   if (MI->mayStore()) {
1060     // Register saves.
1061     assert(DstReg == ARM::SP &&
1062            "Only stack pointer as a destination reg is supported");
1063
1064     SmallVector<unsigned, 4> RegList;
1065     // Skip src & dst reg, and pred ops.
1066     unsigned StartOp = 2 + 2;
1067     // Use all the operands.
1068     unsigned NumOffset = 0;
1069
1070     switch (Opc) {
1071     default:
1072       MI->dump();
1073       llvm_unreachable("Unsupported opcode for unwinding information");
1074     case ARM::tPUSH:
1075       // Special case here: no src & dst reg, but two extra imp ops.
1076       StartOp = 2; NumOffset = 2;
1077     case ARM::STMDB_UPD:
1078     case ARM::t2STMDB_UPD:
1079     case ARM::VSTMDDB_UPD:
1080       assert(SrcReg == ARM::SP &&
1081              "Only stack pointer as a source reg is supported");
1082       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1083            i != NumOps; ++i) {
1084         const MachineOperand &MO = MI->getOperand(i);
1085         // Actually, there should never be any impdef stuff here. Skip it
1086         // temporary to workaround PR11902.
1087         if (MO.isImplicit())
1088           continue;
1089         RegList.push_back(MO.getReg());
1090       }
1091       break;
1092     case ARM::STR_PRE_IMM:
1093     case ARM::STR_PRE_REG:
1094     case ARM::t2STR_PRE:
1095       assert(MI->getOperand(2).getReg() == ARM::SP &&
1096              "Only stack pointer as a source reg is supported");
1097       RegList.push_back(SrcReg);
1098       break;
1099     }
1100     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1101       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1102   } else {
1103     // Changes of stack / frame pointer.
1104     if (SrcReg == ARM::SP) {
1105       int64_t Offset = 0;
1106       switch (Opc) {
1107       default:
1108         MI->dump();
1109         llvm_unreachable("Unsupported opcode for unwinding information");
1110       case ARM::MOVr:
1111       case ARM::tMOVr:
1112         Offset = 0;
1113         break;
1114       case ARM::ADDri:
1115         Offset = -MI->getOperand(2).getImm();
1116         break;
1117       case ARM::SUBri:
1118       case ARM::t2SUBri:
1119         Offset = MI->getOperand(2).getImm();
1120         break;
1121       case ARM::tSUBspi:
1122         Offset = MI->getOperand(2).getImm()*4;
1123         break;
1124       case ARM::tADDspi:
1125       case ARM::tADDrSPi:
1126         Offset = -MI->getOperand(2).getImm()*4;
1127         break;
1128       case ARM::tLDRpci: {
1129         // Grab the constpool index and check, whether it corresponds to
1130         // original or cloned constpool entry.
1131         unsigned CPI = MI->getOperand(1).getIndex();
1132         const MachineConstantPool *MCP = MF.getConstantPool();
1133         if (CPI >= MCP->getConstants().size())
1134           CPI = AFI.getOriginalCPIdx(CPI);
1135         assert(CPI != -1U && "Invalid constpool index");
1136
1137         // Derive the actual offset.
1138         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1139         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1140         // FIXME: Check for user, it should be "add" instruction!
1141         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1142         break;
1143       }
1144       }
1145
1146       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1147         if (DstReg == FramePtr && FramePtr != ARM::SP)
1148           // Set-up of the frame pointer. Positive values correspond to "add"
1149           // instruction.
1150           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1151         else if (DstReg == ARM::SP) {
1152           // Change of SP by an offset. Positive values correspond to "sub"
1153           // instruction.
1154           ATS.emitPad(Offset);
1155         } else {
1156           // Move of SP to a register.  Positive values correspond to an "add"
1157           // instruction.
1158           ATS.emitMovSP(DstReg, -Offset);
1159         }
1160       }
1161     } else if (DstReg == ARM::SP) {
1162       MI->dump();
1163       llvm_unreachable("Unsupported opcode for unwinding information");
1164     }
1165     else {
1166       MI->dump();
1167       llvm_unreachable("Unsupported opcode for unwinding information");
1168     }
1169   }
1170 }
1171
1172 // Simple pseudo-instructions have their lowering (with expansion to real
1173 // instructions) auto-generated.
1174 #include "ARMGenMCPseudoLowering.inc"
1175
1176 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1177   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
1178
1179   // If we just ended a constant pool, mark it as such.
1180   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1181     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1182     InConstantPool = false;
1183   }
1184
1185   // Emit unwinding stuff for frame-related instructions
1186   if (Subtarget->isTargetEHABICompatible() &&
1187        MI->getFlag(MachineInstr::FrameSetup))
1188     EmitUnwindingInstruction(MI);
1189
1190   // Do any auto-generated pseudo lowerings.
1191   if (emitPseudoExpansionLowering(OutStreamer, MI))
1192     return;
1193
1194   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1195          "Pseudo flag setting opcode should be expanded early");
1196
1197   // Check for manual lowerings.
1198   unsigned Opc = MI->getOpcode();
1199   switch (Opc) {
1200   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1201   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1202   case ARM::LEApcrel:
1203   case ARM::tLEApcrel:
1204   case ARM::t2LEApcrel: {
1205     // FIXME: Need to also handle globals and externals
1206     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1207     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1208                                               ARM::t2LEApcrel ? ARM::t2ADR
1209                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1210                      : ARM::ADR))
1211       .addReg(MI->getOperand(0).getReg())
1212       .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
1213       // Add predicate operands.
1214       .addImm(MI->getOperand(2).getImm())
1215       .addReg(MI->getOperand(3).getReg()));
1216     return;
1217   }
1218   case ARM::LEApcrelJT:
1219   case ARM::tLEApcrelJT:
1220   case ARM::t2LEApcrelJT: {
1221     MCSymbol *JTIPICSymbol =
1222       GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
1223                                   MI->getOperand(2).getImm());
1224     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1225                                               ARM::t2LEApcrelJT ? ARM::t2ADR
1226                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1227                      : ARM::ADR))
1228       .addReg(MI->getOperand(0).getReg())
1229       .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
1230       // Add predicate operands.
1231       .addImm(MI->getOperand(3).getImm())
1232       .addReg(MI->getOperand(4).getReg()));
1233     return;
1234   }
1235   // Darwin call instructions are just normal call instructions with different
1236   // clobber semantics (they clobber R9).
1237   case ARM::BX_CALL: {
1238     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1239       .addReg(ARM::LR)
1240       .addReg(ARM::PC)
1241       // Add predicate operands.
1242       .addImm(ARMCC::AL)
1243       .addReg(0)
1244       // Add 's' bit operand (always reg0 for this)
1245       .addReg(0));
1246
1247     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1248       .addReg(MI->getOperand(0).getReg()));
1249     return;
1250   }
1251   case ARM::tBX_CALL: {
1252     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1253       .addReg(ARM::LR)
1254       .addReg(ARM::PC)
1255       // Add predicate operands.
1256       .addImm(ARMCC::AL)
1257       .addReg(0));
1258
1259     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1260       .addReg(MI->getOperand(0).getReg())
1261       // Add predicate operands.
1262       .addImm(ARMCC::AL)
1263       .addReg(0));
1264     return;
1265   }
1266   case ARM::BMOVPCRX_CALL: {
1267     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1268       .addReg(ARM::LR)
1269       .addReg(ARM::PC)
1270       // Add predicate operands.
1271       .addImm(ARMCC::AL)
1272       .addReg(0)
1273       // Add 's' bit operand (always reg0 for this)
1274       .addReg(0));
1275
1276     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1277       .addReg(ARM::PC)
1278       .addReg(MI->getOperand(0).getReg())
1279       // Add predicate operands.
1280       .addImm(ARMCC::AL)
1281       .addReg(0)
1282       // Add 's' bit operand (always reg0 for this)
1283       .addReg(0));
1284     return;
1285   }
1286   case ARM::BMOVPCB_CALL: {
1287     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1288       .addReg(ARM::LR)
1289       .addReg(ARM::PC)
1290       // Add predicate operands.
1291       .addImm(ARMCC::AL)
1292       .addReg(0)
1293       // Add 's' bit operand (always reg0 for this)
1294       .addReg(0));
1295
1296     const MachineOperand &Op = MI->getOperand(0);
1297     const GlobalValue *GV = Op.getGlobal();
1298     const unsigned TF = Op.getTargetFlags();
1299     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1300     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1301     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::Bcc)
1302       .addExpr(GVSymExpr)
1303       // Add predicate operands.
1304       .addImm(ARMCC::AL)
1305       .addReg(0));
1306     return;
1307   }
1308   case ARM::MOVi16_ga_pcrel:
1309   case ARM::t2MOVi16_ga_pcrel: {
1310     MCInst TmpInst;
1311     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1312     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1313
1314     unsigned TF = MI->getOperand(1).getTargetFlags();
1315     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1316     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1317     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1318
1319     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1320                                      getFunctionNumber(),
1321                                      MI->getOperand(2).getImm(), OutContext);
1322     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1323     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1324     const MCExpr *PCRelExpr =
1325       ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
1326                                       MCBinaryExpr::CreateAdd(LabelSymExpr,
1327                                       MCConstantExpr::Create(PCAdj, OutContext),
1328                                       OutContext), OutContext), OutContext);
1329       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1330
1331     // Add predicate operands.
1332     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1333     TmpInst.addOperand(MCOperand::CreateReg(0));
1334     // Add 's' bit operand (always reg0 for this)
1335     TmpInst.addOperand(MCOperand::CreateReg(0));
1336     EmitToStreamer(OutStreamer, TmpInst);
1337     return;
1338   }
1339   case ARM::MOVTi16_ga_pcrel:
1340   case ARM::t2MOVTi16_ga_pcrel: {
1341     MCInst TmpInst;
1342     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1343                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1344     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1345     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1346
1347     unsigned TF = MI->getOperand(2).getTargetFlags();
1348     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1349     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1350     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1351
1352     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1353                                      getFunctionNumber(),
1354                                      MI->getOperand(3).getImm(), OutContext);
1355     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1356     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1357     const MCExpr *PCRelExpr =
1358         ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
1359                                    MCBinaryExpr::CreateAdd(LabelSymExpr,
1360                                       MCConstantExpr::Create(PCAdj, OutContext),
1361                                           OutContext), OutContext), OutContext);
1362       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1363     // Add predicate operands.
1364     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1365     TmpInst.addOperand(MCOperand::CreateReg(0));
1366     // Add 's' bit operand (always reg0 for this)
1367     TmpInst.addOperand(MCOperand::CreateReg(0));
1368     EmitToStreamer(OutStreamer, TmpInst);
1369     return;
1370   }
1371   case ARM::tPICADD: {
1372     // This is a pseudo op for a label + instruction sequence, which looks like:
1373     // LPC0:
1374     //     add r0, pc
1375     // This adds the address of LPC0 to r0.
1376
1377     // Emit the label.
1378     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1379                           getFunctionNumber(), MI->getOperand(2).getImm(),
1380                           OutContext));
1381
1382     // Form and emit the add.
1383     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDhirr)
1384       .addReg(MI->getOperand(0).getReg())
1385       .addReg(MI->getOperand(0).getReg())
1386       .addReg(ARM::PC)
1387       // Add predicate operands.
1388       .addImm(ARMCC::AL)
1389       .addReg(0));
1390     return;
1391   }
1392   case ARM::PICADD: {
1393     // This is a pseudo op for a label + instruction sequence, which looks like:
1394     // LPC0:
1395     //     add r0, pc, r0
1396     // This adds the address of LPC0 to r0.
1397
1398     // Emit the label.
1399     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1400                           getFunctionNumber(), MI->getOperand(2).getImm(),
1401                           OutContext));
1402
1403     // Form and emit the add.
1404     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1405       .addReg(MI->getOperand(0).getReg())
1406       .addReg(ARM::PC)
1407       .addReg(MI->getOperand(1).getReg())
1408       // Add predicate operands.
1409       .addImm(MI->getOperand(3).getImm())
1410       .addReg(MI->getOperand(4).getReg())
1411       // Add 's' bit operand (always reg0 for this)
1412       .addReg(0));
1413     return;
1414   }
1415   case ARM::PICSTR:
1416   case ARM::PICSTRB:
1417   case ARM::PICSTRH:
1418   case ARM::PICLDR:
1419   case ARM::PICLDRB:
1420   case ARM::PICLDRH:
1421   case ARM::PICLDRSB:
1422   case ARM::PICLDRSH: {
1423     // This is a pseudo op for a label + instruction sequence, which looks like:
1424     // LPC0:
1425     //     OP r0, [pc, r0]
1426     // The LCP0 label is referenced by a constant pool entry in order to get
1427     // a PC-relative address at the ldr instruction.
1428
1429     // Emit the label.
1430     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1431                           getFunctionNumber(), MI->getOperand(2).getImm(),
1432                           OutContext));
1433
1434     // Form and emit the load
1435     unsigned Opcode;
1436     switch (MI->getOpcode()) {
1437     default:
1438       llvm_unreachable("Unexpected opcode!");
1439     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1440     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1441     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1442     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1443     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1444     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1445     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1446     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1447     }
1448     EmitToStreamer(OutStreamer, MCInstBuilder(Opcode)
1449       .addReg(MI->getOperand(0).getReg())
1450       .addReg(ARM::PC)
1451       .addReg(MI->getOperand(1).getReg())
1452       .addImm(0)
1453       // Add predicate operands.
1454       .addImm(MI->getOperand(3).getImm())
1455       .addReg(MI->getOperand(4).getReg()));
1456
1457     return;
1458   }
1459   case ARM::CONSTPOOL_ENTRY: {
1460     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1461     /// in the function.  The first operand is the ID# for this instruction, the
1462     /// second is the index into the MachineConstantPool that this is, the third
1463     /// is the size in bytes of this constant pool entry.
1464     /// The required alignment is specified on the basic block holding this MI.
1465     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1466     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1467
1468     // If this is the first entry of the pool, mark it.
1469     if (!InConstantPool) {
1470       OutStreamer.EmitDataRegion(MCDR_DataRegion);
1471       InConstantPool = true;
1472     }
1473
1474     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1475
1476     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1477     if (MCPE.isMachineConstantPoolEntry())
1478       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1479     else
1480       EmitGlobalConstant(MCPE.Val.ConstVal);
1481     return;
1482   }
1483   case ARM::t2BR_JT: {
1484     // Lower and emit the instruction itself, then the jump table following it.
1485     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1486       .addReg(ARM::PC)
1487       .addReg(MI->getOperand(0).getReg())
1488       // Add predicate operands.
1489       .addImm(ARMCC::AL)
1490       .addReg(0));
1491
1492     // Output the data for the jump table itself
1493     EmitJump2Table(MI);
1494     return;
1495   }
1496   case ARM::t2TBB_JT: {
1497     // Lower and emit the instruction itself, then the jump table following it.
1498     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBB)
1499       .addReg(ARM::PC)
1500       .addReg(MI->getOperand(0).getReg())
1501       // Add predicate operands.
1502       .addImm(ARMCC::AL)
1503       .addReg(0));
1504
1505     // Output the data for the jump table itself
1506     EmitJump2Table(MI);
1507     // Make sure the next instruction is 2-byte aligned.
1508     EmitAlignment(1);
1509     return;
1510   }
1511   case ARM::t2TBH_JT: {
1512     // Lower and emit the instruction itself, then the jump table following it.
1513     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBH)
1514       .addReg(ARM::PC)
1515       .addReg(MI->getOperand(0).getReg())
1516       // Add predicate operands.
1517       .addImm(ARMCC::AL)
1518       .addReg(0));
1519
1520     // Output the data for the jump table itself
1521     EmitJump2Table(MI);
1522     return;
1523   }
1524   case ARM::tBR_JTr:
1525   case ARM::BR_JTr: {
1526     // Lower and emit the instruction itself, then the jump table following it.
1527     // mov pc, target
1528     MCInst TmpInst;
1529     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1530       ARM::MOVr : ARM::tMOVr;
1531     TmpInst.setOpcode(Opc);
1532     TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1533     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1534     // Add predicate operands.
1535     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1536     TmpInst.addOperand(MCOperand::CreateReg(0));
1537     // Add 's' bit operand (always reg0 for this)
1538     if (Opc == ARM::MOVr)
1539       TmpInst.addOperand(MCOperand::CreateReg(0));
1540     EmitToStreamer(OutStreamer, TmpInst);
1541
1542     // Make sure the Thumb jump table is 4-byte aligned.
1543     if (Opc == ARM::tMOVr)
1544       EmitAlignment(2);
1545
1546     // Output the data for the jump table itself
1547     EmitJumpTable(MI);
1548     return;
1549   }
1550   case ARM::BR_JTm: {
1551     // Lower and emit the instruction itself, then the jump table following it.
1552     // ldr pc, target
1553     MCInst TmpInst;
1554     if (MI->getOperand(1).getReg() == 0) {
1555       // literal offset
1556       TmpInst.setOpcode(ARM::LDRi12);
1557       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1558       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1559       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1560     } else {
1561       TmpInst.setOpcode(ARM::LDRrs);
1562       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1563       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1564       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1565       TmpInst.addOperand(MCOperand::CreateImm(0));
1566     }
1567     // Add predicate operands.
1568     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1569     TmpInst.addOperand(MCOperand::CreateReg(0));
1570     EmitToStreamer(OutStreamer, TmpInst);
1571
1572     // Output the data for the jump table itself
1573     EmitJumpTable(MI);
1574     return;
1575   }
1576   case ARM::BR_JTadd: {
1577     // Lower and emit the instruction itself, then the jump table following it.
1578     // add pc, target, idx
1579     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1580       .addReg(ARM::PC)
1581       .addReg(MI->getOperand(0).getReg())
1582       .addReg(MI->getOperand(1).getReg())
1583       // Add predicate operands.
1584       .addImm(ARMCC::AL)
1585       .addReg(0)
1586       // Add 's' bit operand (always reg0 for this)
1587       .addReg(0));
1588
1589     // Output the data for the jump table itself
1590     EmitJumpTable(MI);
1591     return;
1592   }
1593   case ARM::TRAP: {
1594     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1595     // FIXME: Remove this special case when they do.
1596     if (!Subtarget->isTargetMachO()) {
1597       //.long 0xe7ffdefe @ trap
1598       uint32_t Val = 0xe7ffdefeUL;
1599       OutStreamer.AddComment("trap");
1600       OutStreamer.EmitIntValue(Val, 4);
1601       return;
1602     }
1603     break;
1604   }
1605   case ARM::TRAPNaCl: {
1606     //.long 0xe7fedef0 @ trap
1607     uint32_t Val = 0xe7fedef0UL;
1608     OutStreamer.AddComment("trap");
1609     OutStreamer.EmitIntValue(Val, 4);
1610     return;
1611   }
1612   case ARM::tTRAP: {
1613     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1614     // FIXME: Remove this special case when they do.
1615     if (!Subtarget->isTargetMachO()) {
1616       //.short 57086 @ trap
1617       uint16_t Val = 0xdefe;
1618       OutStreamer.AddComment("trap");
1619       OutStreamer.EmitIntValue(Val, 2);
1620       return;
1621     }
1622     break;
1623   }
1624   case ARM::t2Int_eh_sjlj_setjmp:
1625   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1626   case ARM::tInt_eh_sjlj_setjmp: {
1627     // Two incoming args: GPR:$src, GPR:$val
1628     // mov $val, pc
1629     // adds $val, #7
1630     // str $val, [$src, #4]
1631     // movs r0, #0
1632     // b 1f
1633     // movs r0, #1
1634     // 1:
1635     unsigned SrcReg = MI->getOperand(0).getReg();
1636     unsigned ValReg = MI->getOperand(1).getReg();
1637     MCSymbol *Label = GetARMSJLJEHLabel();
1638     OutStreamer.AddComment("eh_setjmp begin");
1639     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1640       .addReg(ValReg)
1641       .addReg(ARM::PC)
1642       // Predicate.
1643       .addImm(ARMCC::AL)
1644       .addReg(0));
1645
1646     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDi3)
1647       .addReg(ValReg)
1648       // 's' bit operand
1649       .addReg(ARM::CPSR)
1650       .addReg(ValReg)
1651       .addImm(7)
1652       // Predicate.
1653       .addImm(ARMCC::AL)
1654       .addReg(0));
1655
1656     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tSTRi)
1657       .addReg(ValReg)
1658       .addReg(SrcReg)
1659       // The offset immediate is #4. The operand value is scaled by 4 for the
1660       // tSTR instruction.
1661       .addImm(1)
1662       // Predicate.
1663       .addImm(ARMCC::AL)
1664       .addReg(0));
1665
1666     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1667       .addReg(ARM::R0)
1668       .addReg(ARM::CPSR)
1669       .addImm(0)
1670       // Predicate.
1671       .addImm(ARMCC::AL)
1672       .addReg(0));
1673
1674     const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
1675     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tB)
1676       .addExpr(SymbolExpr)
1677       .addImm(ARMCC::AL)
1678       .addReg(0));
1679
1680     OutStreamer.AddComment("eh_setjmp end");
1681     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1682       .addReg(ARM::R0)
1683       .addReg(ARM::CPSR)
1684       .addImm(1)
1685       // Predicate.
1686       .addImm(ARMCC::AL)
1687       .addReg(0));
1688
1689     OutStreamer.EmitLabel(Label);
1690     return;
1691   }
1692
1693   case ARM::Int_eh_sjlj_setjmp_nofp:
1694   case ARM::Int_eh_sjlj_setjmp: {
1695     // Two incoming args: GPR:$src, GPR:$val
1696     // add $val, pc, #8
1697     // str $val, [$src, #+4]
1698     // mov r0, #0
1699     // add pc, pc, #0
1700     // mov r0, #1
1701     unsigned SrcReg = MI->getOperand(0).getReg();
1702     unsigned ValReg = MI->getOperand(1).getReg();
1703
1704     OutStreamer.AddComment("eh_setjmp begin");
1705     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1706       .addReg(ValReg)
1707       .addReg(ARM::PC)
1708       .addImm(8)
1709       // Predicate.
1710       .addImm(ARMCC::AL)
1711       .addReg(0)
1712       // 's' bit operand (always reg0 for this).
1713       .addReg(0));
1714
1715     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::STRi12)
1716       .addReg(ValReg)
1717       .addReg(SrcReg)
1718       .addImm(4)
1719       // Predicate.
1720       .addImm(ARMCC::AL)
1721       .addReg(0));
1722
1723     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1724       .addReg(ARM::R0)
1725       .addImm(0)
1726       // Predicate.
1727       .addImm(ARMCC::AL)
1728       .addReg(0)
1729       // 's' bit operand (always reg0 for this).
1730       .addReg(0));
1731
1732     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1733       .addReg(ARM::PC)
1734       .addReg(ARM::PC)
1735       .addImm(0)
1736       // Predicate.
1737       .addImm(ARMCC::AL)
1738       .addReg(0)
1739       // 's' bit operand (always reg0 for this).
1740       .addReg(0));
1741
1742     OutStreamer.AddComment("eh_setjmp end");
1743     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1744       .addReg(ARM::R0)
1745       .addImm(1)
1746       // Predicate.
1747       .addImm(ARMCC::AL)
1748       .addReg(0)
1749       // 's' bit operand (always reg0 for this).
1750       .addReg(0));
1751     return;
1752   }
1753   case ARM::Int_eh_sjlj_longjmp: {
1754     // ldr sp, [$src, #8]
1755     // ldr $scratch, [$src, #4]
1756     // ldr r7, [$src]
1757     // bx $scratch
1758     unsigned SrcReg = MI->getOperand(0).getReg();
1759     unsigned ScratchReg = MI->getOperand(1).getReg();
1760     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1761       .addReg(ARM::SP)
1762       .addReg(SrcReg)
1763       .addImm(8)
1764       // Predicate.
1765       .addImm(ARMCC::AL)
1766       .addReg(0));
1767
1768     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1769       .addReg(ScratchReg)
1770       .addReg(SrcReg)
1771       .addImm(4)
1772       // Predicate.
1773       .addImm(ARMCC::AL)
1774       .addReg(0));
1775
1776     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1777       .addReg(ARM::R7)
1778       .addReg(SrcReg)
1779       .addImm(0)
1780       // Predicate.
1781       .addImm(ARMCC::AL)
1782       .addReg(0));
1783
1784     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1785       .addReg(ScratchReg)
1786       // Predicate.
1787       .addImm(ARMCC::AL)
1788       .addReg(0));
1789     return;
1790   }
1791   case ARM::tInt_eh_sjlj_longjmp: {
1792     // ldr $scratch, [$src, #8]
1793     // mov sp, $scratch
1794     // ldr $scratch, [$src, #4]
1795     // ldr r7, [$src]
1796     // bx $scratch
1797     unsigned SrcReg = MI->getOperand(0).getReg();
1798     unsigned ScratchReg = MI->getOperand(1).getReg();
1799     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1800       .addReg(ScratchReg)
1801       .addReg(SrcReg)
1802       // The offset immediate is #8. The operand value is scaled by 4 for the
1803       // tLDR instruction.
1804       .addImm(2)
1805       // Predicate.
1806       .addImm(ARMCC::AL)
1807       .addReg(0));
1808
1809     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1810       .addReg(ARM::SP)
1811       .addReg(ScratchReg)
1812       // Predicate.
1813       .addImm(ARMCC::AL)
1814       .addReg(0));
1815
1816     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1817       .addReg(ScratchReg)
1818       .addReg(SrcReg)
1819       .addImm(1)
1820       // Predicate.
1821       .addImm(ARMCC::AL)
1822       .addReg(0));
1823
1824     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1825       .addReg(ARM::R7)
1826       .addReg(SrcReg)
1827       .addImm(0)
1828       // Predicate.
1829       .addImm(ARMCC::AL)
1830       .addReg(0));
1831
1832     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1833       .addReg(ScratchReg)
1834       // Predicate.
1835       .addImm(ARMCC::AL)
1836       .addReg(0));
1837     return;
1838   }
1839   }
1840
1841   MCInst TmpInst;
1842   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1843
1844   EmitToStreamer(OutStreamer, TmpInst);
1845 }
1846
1847 //===----------------------------------------------------------------------===//
1848 // Target Registry Stuff
1849 //===----------------------------------------------------------------------===//
1850
1851 // Force static initialization.
1852 extern "C" void LLVMInitializeARMAsmPrinter() {
1853   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1854   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1855   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1856   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1857 }