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