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