xref: /freebsd/contrib/llvm-project/llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp (revision c203bd70b5957f85616424b6fa374479372d06e3)
1 //===-- PPCAsmParser.cpp - Parse PowerPC asm to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MCTargetDesc/PPCMCExpr.h"
10 #include "MCTargetDesc/PPCMCTargetDesc.h"
11 #include "PPCTargetStreamer.h"
12 #include "TargetInfo/PowerPCTargetInfo.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCInstrInfo.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbolELF.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace llvm;
32 
33 DEFINE_PPC_REGCLASSES;
34 
35 // Evaluate an expression containing condition register
36 // or condition register field symbols.  Returns positive
37 // value on success, or -1 on error.
38 static int64_t
39 EvaluateCRExpr(const MCExpr *E) {
40   switch (E->getKind()) {
41   case MCExpr::Target:
42     return -1;
43 
44   case MCExpr::Constant: {
45     int64_t Res = cast<MCConstantExpr>(E)->getValue();
46     return Res < 0 ? -1 : Res;
47   }
48 
49   case MCExpr::SymbolRef: {
50     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
51     StringRef Name = SRE->getSymbol().getName();
52 
53     if (Name == "lt") return 0;
54     if (Name == "gt") return 1;
55     if (Name == "eq") return 2;
56     if (Name == "so") return 3;
57     if (Name == "un") return 3;
58 
59     if (Name == "cr0") return 0;
60     if (Name == "cr1") return 1;
61     if (Name == "cr2") return 2;
62     if (Name == "cr3") return 3;
63     if (Name == "cr4") return 4;
64     if (Name == "cr5") return 5;
65     if (Name == "cr6") return 6;
66     if (Name == "cr7") return 7;
67 
68     return -1;
69   }
70 
71   case MCExpr::Unary:
72     return -1;
73 
74   case MCExpr::Binary: {
75     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
76     int64_t LHSVal = EvaluateCRExpr(BE->getLHS());
77     int64_t RHSVal = EvaluateCRExpr(BE->getRHS());
78     int64_t Res;
79 
80     if (LHSVal < 0 || RHSVal < 0)
81       return -1;
82 
83     switch (BE->getOpcode()) {
84     default: return -1;
85     case MCBinaryExpr::Add: Res = LHSVal + RHSVal; break;
86     case MCBinaryExpr::Mul: Res = LHSVal * RHSVal; break;
87     }
88 
89     return Res < 0 ? -1 : Res;
90   }
91   }
92 
93   llvm_unreachable("Invalid expression kind!");
94 }
95 
96 namespace {
97 
98 struct PPCOperand;
99 
100 class PPCAsmParser : public MCTargetAsmParser {
101   bool IsPPC64;
102   bool IsDarwin;
103 
104   void Warning(SMLoc L, const Twine &Msg) { getParser().Warning(L, Msg); }
105 
106   bool isPPC64() const { return IsPPC64; }
107   bool isDarwin() const { return IsDarwin; }
108 
109   bool MatchRegisterName(unsigned &RegNo, int64_t &IntVal);
110 
111   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
112   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
113                                         SMLoc &EndLoc) override;
114 
115   const MCExpr *ExtractModifierFromExpr(const MCExpr *E,
116                                         PPCMCExpr::VariantKind &Variant);
117   const MCExpr *FixupVariantKind(const MCExpr *E);
118   bool ParseExpression(const MCExpr *&EVal);
119   bool ParseDarwinExpression(const MCExpr *&EVal);
120 
121   bool ParseOperand(OperandVector &Operands);
122 
123   bool ParseDirectiveWord(unsigned Size, AsmToken ID);
124   bool ParseDirectiveTC(unsigned Size, AsmToken ID);
125   bool ParseDirectiveMachine(SMLoc L);
126   bool ParseDarwinDirectiveMachine(SMLoc L);
127   bool ParseDirectiveAbiVersion(SMLoc L);
128   bool ParseDirectiveLocalEntry(SMLoc L);
129 
130   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
131                                OperandVector &Operands, MCStreamer &Out,
132                                uint64_t &ErrorInfo,
133                                bool MatchingInlineAsm) override;
134 
135   void ProcessInstruction(MCInst &Inst, const OperandVector &Ops);
136 
137   /// @name Auto-generated Match Functions
138   /// {
139 
140 #define GET_ASSEMBLER_HEADER
141 #include "PPCGenAsmMatcher.inc"
142 
143   /// }
144 
145 
146 public:
147   PPCAsmParser(const MCSubtargetInfo &STI, MCAsmParser &,
148                const MCInstrInfo &MII, const MCTargetOptions &Options)
149     : MCTargetAsmParser(Options, STI, MII) {
150     // Check for 64-bit vs. 32-bit pointer mode.
151     const Triple &TheTriple = STI.getTargetTriple();
152     IsPPC64 = TheTriple.isPPC64();
153     IsDarwin = TheTriple.isMacOSX();
154     // Initialize the set of available features.
155     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
156   }
157 
158   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
159                         SMLoc NameLoc, OperandVector &Operands) override;
160 
161   bool ParseDirective(AsmToken DirectiveID) override;
162 
163   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
164                                       unsigned Kind) override;
165 
166   const MCExpr *applyModifierToExpr(const MCExpr *E,
167                                     MCSymbolRefExpr::VariantKind,
168                                     MCContext &Ctx) override;
169 };
170 
171 /// PPCOperand - Instances of this class represent a parsed PowerPC machine
172 /// instruction.
173 struct PPCOperand : public MCParsedAsmOperand {
174   enum KindTy {
175     Token,
176     Immediate,
177     ContextImmediate,
178     Expression,
179     TLSRegister
180   } Kind;
181 
182   SMLoc StartLoc, EndLoc;
183   bool IsPPC64;
184 
185   struct TokOp {
186     const char *Data;
187     unsigned Length;
188   };
189 
190   struct ImmOp {
191     int64_t Val;
192   };
193 
194   struct ExprOp {
195     const MCExpr *Val;
196     int64_t CRVal;     // Cached result of EvaluateCRExpr(Val)
197   };
198 
199   struct TLSRegOp {
200     const MCSymbolRefExpr *Sym;
201   };
202 
203   union {
204     struct TokOp Tok;
205     struct ImmOp Imm;
206     struct ExprOp Expr;
207     struct TLSRegOp TLSReg;
208   };
209 
210   PPCOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
211 public:
212   PPCOperand(const PPCOperand &o) : MCParsedAsmOperand() {
213     Kind = o.Kind;
214     StartLoc = o.StartLoc;
215     EndLoc = o.EndLoc;
216     IsPPC64 = o.IsPPC64;
217     switch (Kind) {
218     case Token:
219       Tok = o.Tok;
220       break;
221     case Immediate:
222     case ContextImmediate:
223       Imm = o.Imm;
224       break;
225     case Expression:
226       Expr = o.Expr;
227       break;
228     case TLSRegister:
229       TLSReg = o.TLSReg;
230       break;
231     }
232   }
233 
234   // Disable use of sized deallocation due to overallocation of PPCOperand
235   // objects in CreateTokenWithStringCopy.
236   void operator delete(void *p) { ::operator delete(p); }
237 
238   /// getStartLoc - Get the location of the first token of this operand.
239   SMLoc getStartLoc() const override { return StartLoc; }
240 
241   /// getEndLoc - Get the location of the last token of this operand.
242   SMLoc getEndLoc() const override { return EndLoc; }
243 
244   /// getLocRange - Get the range between the first and last token of this
245   /// operand.
246   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
247 
248   /// isPPC64 - True if this operand is for an instruction in 64-bit mode.
249   bool isPPC64() const { return IsPPC64; }
250 
251   int64_t getImm() const {
252     assert(Kind == Immediate && "Invalid access!");
253     return Imm.Val;
254   }
255   int64_t getImmS16Context() const {
256     assert((Kind == Immediate || Kind == ContextImmediate) &&
257            "Invalid access!");
258     if (Kind == Immediate)
259       return Imm.Val;
260     return static_cast<int16_t>(Imm.Val);
261   }
262   int64_t getImmU16Context() const {
263     assert((Kind == Immediate || Kind == ContextImmediate) &&
264            "Invalid access!");
265     return Imm.Val;
266   }
267 
268   const MCExpr *getExpr() const {
269     assert(Kind == Expression && "Invalid access!");
270     return Expr.Val;
271   }
272 
273   int64_t getExprCRVal() const {
274     assert(Kind == Expression && "Invalid access!");
275     return Expr.CRVal;
276   }
277 
278   const MCExpr *getTLSReg() const {
279     assert(Kind == TLSRegister && "Invalid access!");
280     return TLSReg.Sym;
281   }
282 
283   unsigned getReg() const override {
284     assert(isRegNumber() && "Invalid access!");
285     return (unsigned) Imm.Val;
286   }
287 
288   unsigned getVSReg() const {
289     assert(isVSRegNumber() && "Invalid access!");
290     return (unsigned) Imm.Val;
291   }
292 
293   unsigned getCCReg() const {
294     assert(isCCRegNumber() && "Invalid access!");
295     return (unsigned) (Kind == Immediate ? Imm.Val : Expr.CRVal);
296   }
297 
298   unsigned getCRBit() const {
299     assert(isCRBitNumber() && "Invalid access!");
300     return (unsigned) (Kind == Immediate ? Imm.Val : Expr.CRVal);
301   }
302 
303   unsigned getCRBitMask() const {
304     assert(isCRBitMask() && "Invalid access!");
305     return 7 - countTrailingZeros<uint64_t>(Imm.Val);
306   }
307 
308   bool isToken() const override { return Kind == Token; }
309   bool isImm() const override {
310     return Kind == Immediate || Kind == Expression;
311   }
312   bool isU1Imm() const { return Kind == Immediate && isUInt<1>(getImm()); }
313   bool isU2Imm() const { return Kind == Immediate && isUInt<2>(getImm()); }
314   bool isU3Imm() const { return Kind == Immediate && isUInt<3>(getImm()); }
315   bool isU4Imm() const { return Kind == Immediate && isUInt<4>(getImm()); }
316   bool isU5Imm() const { return Kind == Immediate && isUInt<5>(getImm()); }
317   bool isS5Imm() const { return Kind == Immediate && isInt<5>(getImm()); }
318   bool isU6Imm() const { return Kind == Immediate && isUInt<6>(getImm()); }
319   bool isU6ImmX2() const { return Kind == Immediate &&
320                                   isUInt<6>(getImm()) &&
321                                   (getImm() & 1) == 0; }
322   bool isU7Imm() const { return Kind == Immediate && isUInt<7>(getImm()); }
323   bool isU7ImmX4() const { return Kind == Immediate &&
324                                   isUInt<7>(getImm()) &&
325                                   (getImm() & 3) == 0; }
326   bool isU8Imm() const { return Kind == Immediate && isUInt<8>(getImm()); }
327   bool isU8ImmX8() const { return Kind == Immediate &&
328                                   isUInt<8>(getImm()) &&
329                                   (getImm() & 7) == 0; }
330 
331   bool isU10Imm() const { return Kind == Immediate && isUInt<10>(getImm()); }
332   bool isU12Imm() const { return Kind == Immediate && isUInt<12>(getImm()); }
333   bool isU16Imm() const {
334     switch (Kind) {
335       case Expression:
336         return true;
337       case Immediate:
338       case ContextImmediate:
339         return isUInt<16>(getImmU16Context());
340       default:
341         return false;
342     }
343   }
344   bool isS16Imm() const {
345     switch (Kind) {
346       case Expression:
347         return true;
348       case Immediate:
349       case ContextImmediate:
350         return isInt<16>(getImmS16Context());
351       default:
352         return false;
353     }
354   }
355   bool isS16ImmX4() const { return Kind == Expression ||
356                                    (Kind == Immediate && isInt<16>(getImm()) &&
357                                     (getImm() & 3) == 0); }
358   bool isS16ImmX16() const { return Kind == Expression ||
359                                     (Kind == Immediate && isInt<16>(getImm()) &&
360                                      (getImm() & 15) == 0); }
361   bool isS34ImmX16() const {
362     return Kind == Expression ||
363            (Kind == Immediate && isInt<34>(getImm()) && (getImm() & 15) == 0);
364   }
365   bool isS34Imm() const {
366     // Once the PC-Rel ABI is finalized, evaluate whether a 34-bit
367     // ContextImmediate is needed.
368     return Kind == Expression || (Kind == Immediate && isInt<34>(getImm()));
369   }
370 
371   bool isS17Imm() const {
372     switch (Kind) {
373       case Expression:
374         return true;
375       case Immediate:
376       case ContextImmediate:
377         return isInt<17>(getImmS16Context());
378       default:
379         return false;
380     }
381   }
382   bool isTLSReg() const { return Kind == TLSRegister; }
383   bool isDirectBr() const {
384     if (Kind == Expression)
385       return true;
386     if (Kind != Immediate)
387       return false;
388     // Operand must be 64-bit aligned, signed 27-bit immediate.
389     if ((getImm() & 3) != 0)
390       return false;
391     if (isInt<26>(getImm()))
392       return true;
393     if (!IsPPC64) {
394       // In 32-bit mode, large 32-bit quantities wrap around.
395       if (isUInt<32>(getImm()) && isInt<26>(static_cast<int32_t>(getImm())))
396         return true;
397     }
398     return false;
399   }
400   bool isCondBr() const { return Kind == Expression ||
401                                  (Kind == Immediate && isInt<16>(getImm()) &&
402                                   (getImm() & 3) == 0); }
403   bool isImmZero() const { return Kind == Immediate && getImm() == 0; }
404   bool isRegNumber() const { return Kind == Immediate && isUInt<5>(getImm()); }
405   bool isVSRegNumber() const {
406     return Kind == Immediate && isUInt<6>(getImm());
407   }
408   bool isCCRegNumber() const { return (Kind == Expression
409                                        && isUInt<3>(getExprCRVal())) ||
410                                       (Kind == Immediate
411                                        && isUInt<3>(getImm())); }
412   bool isCRBitNumber() const { return (Kind == Expression
413                                        && isUInt<5>(getExprCRVal())) ||
414                                       (Kind == Immediate
415                                        && isUInt<5>(getImm())); }
416   bool isCRBitMask() const { return Kind == Immediate && isUInt<8>(getImm()) &&
417                                     isPowerOf2_32(getImm()); }
418   bool isATBitsAsHint() const { return false; }
419   bool isMem() const override { return false; }
420   bool isReg() const override { return false; }
421 
422   void addRegOperands(MCInst &Inst, unsigned N) const {
423     llvm_unreachable("addRegOperands");
424   }
425 
426   void addRegGPRCOperands(MCInst &Inst, unsigned N) const {
427     assert(N == 1 && "Invalid number of operands!");
428     Inst.addOperand(MCOperand::createReg(RRegs[getReg()]));
429   }
430 
431   void addRegGPRCNoR0Operands(MCInst &Inst, unsigned N) const {
432     assert(N == 1 && "Invalid number of operands!");
433     Inst.addOperand(MCOperand::createReg(RRegsNoR0[getReg()]));
434   }
435 
436   void addRegG8RCOperands(MCInst &Inst, unsigned N) const {
437     assert(N == 1 && "Invalid number of operands!");
438     Inst.addOperand(MCOperand::createReg(XRegs[getReg()]));
439   }
440 
441   void addRegG8RCNoX0Operands(MCInst &Inst, unsigned N) const {
442     assert(N == 1 && "Invalid number of operands!");
443     Inst.addOperand(MCOperand::createReg(XRegsNoX0[getReg()]));
444   }
445 
446   void addRegGxRCOperands(MCInst &Inst, unsigned N) const {
447     if (isPPC64())
448       addRegG8RCOperands(Inst, N);
449     else
450       addRegGPRCOperands(Inst, N);
451   }
452 
453   void addRegGxRCNoR0Operands(MCInst &Inst, unsigned N) const {
454     if (isPPC64())
455       addRegG8RCNoX0Operands(Inst, N);
456     else
457       addRegGPRCNoR0Operands(Inst, N);
458   }
459 
460   void addRegF4RCOperands(MCInst &Inst, unsigned N) const {
461     assert(N == 1 && "Invalid number of operands!");
462     Inst.addOperand(MCOperand::createReg(FRegs[getReg()]));
463   }
464 
465   void addRegF8RCOperands(MCInst &Inst, unsigned N) const {
466     assert(N == 1 && "Invalid number of operands!");
467     Inst.addOperand(MCOperand::createReg(FRegs[getReg()]));
468   }
469 
470   void addRegVFRCOperands(MCInst &Inst, unsigned N) const {
471     assert(N == 1 && "Invalid number of operands!");
472     Inst.addOperand(MCOperand::createReg(VFRegs[getReg()]));
473   }
474 
475   void addRegVRRCOperands(MCInst &Inst, unsigned N) const {
476     assert(N == 1 && "Invalid number of operands!");
477     Inst.addOperand(MCOperand::createReg(VRegs[getReg()]));
478   }
479 
480   void addRegVSRCOperands(MCInst &Inst, unsigned N) const {
481     assert(N == 1 && "Invalid number of operands!");
482     Inst.addOperand(MCOperand::createReg(VSRegs[getVSReg()]));
483   }
484 
485   void addRegVSFRCOperands(MCInst &Inst, unsigned N) const {
486     assert(N == 1 && "Invalid number of operands!");
487     Inst.addOperand(MCOperand::createReg(VSFRegs[getVSReg()]));
488   }
489 
490   void addRegVSSRCOperands(MCInst &Inst, unsigned N) const {
491     assert(N == 1 && "Invalid number of operands!");
492     Inst.addOperand(MCOperand::createReg(VSSRegs[getVSReg()]));
493   }
494 
495   void addRegQFRCOperands(MCInst &Inst, unsigned N) const {
496     assert(N == 1 && "Invalid number of operands!");
497     Inst.addOperand(MCOperand::createReg(QFRegs[getReg()]));
498   }
499 
500   void addRegQSRCOperands(MCInst &Inst, unsigned N) const {
501     assert(N == 1 && "Invalid number of operands!");
502     Inst.addOperand(MCOperand::createReg(QFRegs[getReg()]));
503   }
504 
505   void addRegQBRCOperands(MCInst &Inst, unsigned N) const {
506     assert(N == 1 && "Invalid number of operands!");
507     Inst.addOperand(MCOperand::createReg(QFRegs[getReg()]));
508   }
509 
510   void addRegSPE4RCOperands(MCInst &Inst, unsigned N) const {
511     assert(N == 1 && "Invalid number of operands!");
512     Inst.addOperand(MCOperand::createReg(RRegs[getReg()]));
513   }
514 
515   void addRegSPERCOperands(MCInst &Inst, unsigned N) const {
516     assert(N == 1 && "Invalid number of operands!");
517     Inst.addOperand(MCOperand::createReg(SPERegs[getReg()]));
518   }
519 
520   void addRegCRBITRCOperands(MCInst &Inst, unsigned N) const {
521     assert(N == 1 && "Invalid number of operands!");
522     Inst.addOperand(MCOperand::createReg(CRBITRegs[getCRBit()]));
523   }
524 
525   void addRegCRRCOperands(MCInst &Inst, unsigned N) const {
526     assert(N == 1 && "Invalid number of operands!");
527     Inst.addOperand(MCOperand::createReg(CRRegs[getCCReg()]));
528   }
529 
530   void addCRBitMaskOperands(MCInst &Inst, unsigned N) const {
531     assert(N == 1 && "Invalid number of operands!");
532     Inst.addOperand(MCOperand::createReg(CRRegs[getCRBitMask()]));
533   }
534 
535   void addImmOperands(MCInst &Inst, unsigned N) const {
536     assert(N == 1 && "Invalid number of operands!");
537     if (Kind == Immediate)
538       Inst.addOperand(MCOperand::createImm(getImm()));
539     else
540       Inst.addOperand(MCOperand::createExpr(getExpr()));
541   }
542 
543   void addS16ImmOperands(MCInst &Inst, unsigned N) const {
544     assert(N == 1 && "Invalid number of operands!");
545     switch (Kind) {
546       case Immediate:
547         Inst.addOperand(MCOperand::createImm(getImm()));
548         break;
549       case ContextImmediate:
550         Inst.addOperand(MCOperand::createImm(getImmS16Context()));
551         break;
552       default:
553         Inst.addOperand(MCOperand::createExpr(getExpr()));
554         break;
555     }
556   }
557 
558   void addU16ImmOperands(MCInst &Inst, unsigned N) const {
559     assert(N == 1 && "Invalid number of operands!");
560     switch (Kind) {
561       case Immediate:
562         Inst.addOperand(MCOperand::createImm(getImm()));
563         break;
564       case ContextImmediate:
565         Inst.addOperand(MCOperand::createImm(getImmU16Context()));
566         break;
567       default:
568         Inst.addOperand(MCOperand::createExpr(getExpr()));
569         break;
570     }
571   }
572 
573   void addBranchTargetOperands(MCInst &Inst, unsigned N) const {
574     assert(N == 1 && "Invalid number of operands!");
575     if (Kind == Immediate)
576       Inst.addOperand(MCOperand::createImm(getImm() / 4));
577     else
578       Inst.addOperand(MCOperand::createExpr(getExpr()));
579   }
580 
581   void addTLSRegOperands(MCInst &Inst, unsigned N) const {
582     assert(N == 1 && "Invalid number of operands!");
583     Inst.addOperand(MCOperand::createExpr(getTLSReg()));
584   }
585 
586   StringRef getToken() const {
587     assert(Kind == Token && "Invalid access!");
588     return StringRef(Tok.Data, Tok.Length);
589   }
590 
591   void print(raw_ostream &OS) const override;
592 
593   static std::unique_ptr<PPCOperand> CreateToken(StringRef Str, SMLoc S,
594                                                  bool IsPPC64) {
595     auto Op = std::make_unique<PPCOperand>(Token);
596     Op->Tok.Data = Str.data();
597     Op->Tok.Length = Str.size();
598     Op->StartLoc = S;
599     Op->EndLoc = S;
600     Op->IsPPC64 = IsPPC64;
601     return Op;
602   }
603 
604   static std::unique_ptr<PPCOperand>
605   CreateTokenWithStringCopy(StringRef Str, SMLoc S, bool IsPPC64) {
606     // Allocate extra memory for the string and copy it.
607     // FIXME: This is incorrect, Operands are owned by unique_ptr with a default
608     // deleter which will destroy them by simply using "delete", not correctly
609     // calling operator delete on this extra memory after calling the dtor
610     // explicitly.
611     void *Mem = ::operator new(sizeof(PPCOperand) + Str.size());
612     std::unique_ptr<PPCOperand> Op(new (Mem) PPCOperand(Token));
613     Op->Tok.Data = reinterpret_cast<const char *>(Op.get() + 1);
614     Op->Tok.Length = Str.size();
615     std::memcpy(const_cast<char *>(Op->Tok.Data), Str.data(), Str.size());
616     Op->StartLoc = S;
617     Op->EndLoc = S;
618     Op->IsPPC64 = IsPPC64;
619     return Op;
620   }
621 
622   static std::unique_ptr<PPCOperand> CreateImm(int64_t Val, SMLoc S, SMLoc E,
623                                                bool IsPPC64) {
624     auto Op = std::make_unique<PPCOperand>(Immediate);
625     Op->Imm.Val = Val;
626     Op->StartLoc = S;
627     Op->EndLoc = E;
628     Op->IsPPC64 = IsPPC64;
629     return Op;
630   }
631 
632   static std::unique_ptr<PPCOperand> CreateExpr(const MCExpr *Val, SMLoc S,
633                                                 SMLoc E, bool IsPPC64) {
634     auto Op = std::make_unique<PPCOperand>(Expression);
635     Op->Expr.Val = Val;
636     Op->Expr.CRVal = EvaluateCRExpr(Val);
637     Op->StartLoc = S;
638     Op->EndLoc = E;
639     Op->IsPPC64 = IsPPC64;
640     return Op;
641   }
642 
643   static std::unique_ptr<PPCOperand>
644   CreateTLSReg(const MCSymbolRefExpr *Sym, SMLoc S, SMLoc E, bool IsPPC64) {
645     auto Op = std::make_unique<PPCOperand>(TLSRegister);
646     Op->TLSReg.Sym = Sym;
647     Op->StartLoc = S;
648     Op->EndLoc = E;
649     Op->IsPPC64 = IsPPC64;
650     return Op;
651   }
652 
653   static std::unique_ptr<PPCOperand>
654   CreateContextImm(int64_t Val, SMLoc S, SMLoc E, bool IsPPC64) {
655     auto Op = std::make_unique<PPCOperand>(ContextImmediate);
656     Op->Imm.Val = Val;
657     Op->StartLoc = S;
658     Op->EndLoc = E;
659     Op->IsPPC64 = IsPPC64;
660     return Op;
661   }
662 
663   static std::unique_ptr<PPCOperand>
664   CreateFromMCExpr(const MCExpr *Val, SMLoc S, SMLoc E, bool IsPPC64) {
665     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Val))
666       return CreateImm(CE->getValue(), S, E, IsPPC64);
667 
668     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Val))
669       if (SRE->getKind() == MCSymbolRefExpr::VK_PPC_TLS)
670         return CreateTLSReg(SRE, S, E, IsPPC64);
671 
672     if (const PPCMCExpr *TE = dyn_cast<PPCMCExpr>(Val)) {
673       int64_t Res;
674       if (TE->evaluateAsConstant(Res))
675         return CreateContextImm(Res, S, E, IsPPC64);
676     }
677 
678     return CreateExpr(Val, S, E, IsPPC64);
679   }
680 };
681 
682 } // end anonymous namespace.
683 
684 void PPCOperand::print(raw_ostream &OS) const {
685   switch (Kind) {
686   case Token:
687     OS << "'" << getToken() << "'";
688     break;
689   case Immediate:
690   case ContextImmediate:
691     OS << getImm();
692     break;
693   case Expression:
694     OS << *getExpr();
695     break;
696   case TLSRegister:
697     OS << *getTLSReg();
698     break;
699   }
700 }
701 
702 static void
703 addNegOperand(MCInst &Inst, MCOperand &Op, MCContext &Ctx) {
704   if (Op.isImm()) {
705     Inst.addOperand(MCOperand::createImm(-Op.getImm()));
706     return;
707   }
708   const MCExpr *Expr = Op.getExpr();
709   if (const MCUnaryExpr *UnExpr = dyn_cast<MCUnaryExpr>(Expr)) {
710     if (UnExpr->getOpcode() == MCUnaryExpr::Minus) {
711       Inst.addOperand(MCOperand::createExpr(UnExpr->getSubExpr()));
712       return;
713     }
714   } else if (const MCBinaryExpr *BinExpr = dyn_cast<MCBinaryExpr>(Expr)) {
715     if (BinExpr->getOpcode() == MCBinaryExpr::Sub) {
716       const MCExpr *NE = MCBinaryExpr::createSub(BinExpr->getRHS(),
717                                                  BinExpr->getLHS(), Ctx);
718       Inst.addOperand(MCOperand::createExpr(NE));
719       return;
720     }
721   }
722   Inst.addOperand(MCOperand::createExpr(MCUnaryExpr::createMinus(Expr, Ctx)));
723 }
724 
725 void PPCAsmParser::ProcessInstruction(MCInst &Inst,
726                                       const OperandVector &Operands) {
727   int Opcode = Inst.getOpcode();
728   switch (Opcode) {
729   case PPC::DCBTx:
730   case PPC::DCBTT:
731   case PPC::DCBTSTx:
732   case PPC::DCBTSTT: {
733     MCInst TmpInst;
734     TmpInst.setOpcode((Opcode == PPC::DCBTx || Opcode == PPC::DCBTT) ?
735                       PPC::DCBT : PPC::DCBTST);
736     TmpInst.addOperand(MCOperand::createImm(
737       (Opcode == PPC::DCBTx || Opcode == PPC::DCBTSTx) ? 0 : 16));
738     TmpInst.addOperand(Inst.getOperand(0));
739     TmpInst.addOperand(Inst.getOperand(1));
740     Inst = TmpInst;
741     break;
742   }
743   case PPC::DCBTCT:
744   case PPC::DCBTDS: {
745     MCInst TmpInst;
746     TmpInst.setOpcode(PPC::DCBT);
747     TmpInst.addOperand(Inst.getOperand(2));
748     TmpInst.addOperand(Inst.getOperand(0));
749     TmpInst.addOperand(Inst.getOperand(1));
750     Inst = TmpInst;
751     break;
752   }
753   case PPC::DCBTSTCT:
754   case PPC::DCBTSTDS: {
755     MCInst TmpInst;
756     TmpInst.setOpcode(PPC::DCBTST);
757     TmpInst.addOperand(Inst.getOperand(2));
758     TmpInst.addOperand(Inst.getOperand(0));
759     TmpInst.addOperand(Inst.getOperand(1));
760     Inst = TmpInst;
761     break;
762   }
763   case PPC::DCBFx:
764   case PPC::DCBFL:
765   case PPC::DCBFLP: {
766     int L = 0;
767     if (Opcode == PPC::DCBFL)
768       L = 1;
769     else if (Opcode == PPC::DCBFLP)
770       L = 3;
771 
772     MCInst TmpInst;
773     TmpInst.setOpcode(PPC::DCBF);
774     TmpInst.addOperand(MCOperand::createImm(L));
775     TmpInst.addOperand(Inst.getOperand(0));
776     TmpInst.addOperand(Inst.getOperand(1));
777     Inst = TmpInst;
778     break;
779   }
780   case PPC::LAx: {
781     MCInst TmpInst;
782     TmpInst.setOpcode(PPC::LA);
783     TmpInst.addOperand(Inst.getOperand(0));
784     TmpInst.addOperand(Inst.getOperand(2));
785     TmpInst.addOperand(Inst.getOperand(1));
786     Inst = TmpInst;
787     break;
788   }
789   case PPC::SUBI: {
790     MCInst TmpInst;
791     TmpInst.setOpcode(PPC::ADDI);
792     TmpInst.addOperand(Inst.getOperand(0));
793     TmpInst.addOperand(Inst.getOperand(1));
794     addNegOperand(TmpInst, Inst.getOperand(2), getContext());
795     Inst = TmpInst;
796     break;
797   }
798   case PPC::SUBIS: {
799     MCInst TmpInst;
800     TmpInst.setOpcode(PPC::ADDIS);
801     TmpInst.addOperand(Inst.getOperand(0));
802     TmpInst.addOperand(Inst.getOperand(1));
803     addNegOperand(TmpInst, Inst.getOperand(2), getContext());
804     Inst = TmpInst;
805     break;
806   }
807   case PPC::SUBIC: {
808     MCInst TmpInst;
809     TmpInst.setOpcode(PPC::ADDIC);
810     TmpInst.addOperand(Inst.getOperand(0));
811     TmpInst.addOperand(Inst.getOperand(1));
812     addNegOperand(TmpInst, Inst.getOperand(2), getContext());
813     Inst = TmpInst;
814     break;
815   }
816   case PPC::SUBIC_rec: {
817     MCInst TmpInst;
818     TmpInst.setOpcode(PPC::ADDIC_rec);
819     TmpInst.addOperand(Inst.getOperand(0));
820     TmpInst.addOperand(Inst.getOperand(1));
821     addNegOperand(TmpInst, Inst.getOperand(2), getContext());
822     Inst = TmpInst;
823     break;
824   }
825   case PPC::EXTLWI:
826   case PPC::EXTLWI_rec: {
827     MCInst TmpInst;
828     int64_t N = Inst.getOperand(2).getImm();
829     int64_t B = Inst.getOperand(3).getImm();
830     TmpInst.setOpcode(Opcode == PPC::EXTLWI ? PPC::RLWINM : PPC::RLWINM_rec);
831     TmpInst.addOperand(Inst.getOperand(0));
832     TmpInst.addOperand(Inst.getOperand(1));
833     TmpInst.addOperand(MCOperand::createImm(B));
834     TmpInst.addOperand(MCOperand::createImm(0));
835     TmpInst.addOperand(MCOperand::createImm(N - 1));
836     Inst = TmpInst;
837     break;
838   }
839   case PPC::EXTRWI:
840   case PPC::EXTRWI_rec: {
841     MCInst TmpInst;
842     int64_t N = Inst.getOperand(2).getImm();
843     int64_t B = Inst.getOperand(3).getImm();
844     TmpInst.setOpcode(Opcode == PPC::EXTRWI ? PPC::RLWINM : PPC::RLWINM_rec);
845     TmpInst.addOperand(Inst.getOperand(0));
846     TmpInst.addOperand(Inst.getOperand(1));
847     TmpInst.addOperand(MCOperand::createImm(B + N));
848     TmpInst.addOperand(MCOperand::createImm(32 - N));
849     TmpInst.addOperand(MCOperand::createImm(31));
850     Inst = TmpInst;
851     break;
852   }
853   case PPC::INSLWI:
854   case PPC::INSLWI_rec: {
855     MCInst TmpInst;
856     int64_t N = Inst.getOperand(2).getImm();
857     int64_t B = Inst.getOperand(3).getImm();
858     TmpInst.setOpcode(Opcode == PPC::INSLWI ? PPC::RLWIMI : PPC::RLWIMI_rec);
859     TmpInst.addOperand(Inst.getOperand(0));
860     TmpInst.addOperand(Inst.getOperand(0));
861     TmpInst.addOperand(Inst.getOperand(1));
862     TmpInst.addOperand(MCOperand::createImm(32 - B));
863     TmpInst.addOperand(MCOperand::createImm(B));
864     TmpInst.addOperand(MCOperand::createImm((B + N) - 1));
865     Inst = TmpInst;
866     break;
867   }
868   case PPC::INSRWI:
869   case PPC::INSRWI_rec: {
870     MCInst TmpInst;
871     int64_t N = Inst.getOperand(2).getImm();
872     int64_t B = Inst.getOperand(3).getImm();
873     TmpInst.setOpcode(Opcode == PPC::INSRWI ? PPC::RLWIMI : PPC::RLWIMI_rec);
874     TmpInst.addOperand(Inst.getOperand(0));
875     TmpInst.addOperand(Inst.getOperand(0));
876     TmpInst.addOperand(Inst.getOperand(1));
877     TmpInst.addOperand(MCOperand::createImm(32 - (B + N)));
878     TmpInst.addOperand(MCOperand::createImm(B));
879     TmpInst.addOperand(MCOperand::createImm((B + N) - 1));
880     Inst = TmpInst;
881     break;
882   }
883   case PPC::ROTRWI:
884   case PPC::ROTRWI_rec: {
885     MCInst TmpInst;
886     int64_t N = Inst.getOperand(2).getImm();
887     TmpInst.setOpcode(Opcode == PPC::ROTRWI ? PPC::RLWINM : PPC::RLWINM_rec);
888     TmpInst.addOperand(Inst.getOperand(0));
889     TmpInst.addOperand(Inst.getOperand(1));
890     TmpInst.addOperand(MCOperand::createImm(32 - N));
891     TmpInst.addOperand(MCOperand::createImm(0));
892     TmpInst.addOperand(MCOperand::createImm(31));
893     Inst = TmpInst;
894     break;
895   }
896   case PPC::SLWI:
897   case PPC::SLWI_rec: {
898     MCInst TmpInst;
899     int64_t N = Inst.getOperand(2).getImm();
900     TmpInst.setOpcode(Opcode == PPC::SLWI ? PPC::RLWINM : PPC::RLWINM_rec);
901     TmpInst.addOperand(Inst.getOperand(0));
902     TmpInst.addOperand(Inst.getOperand(1));
903     TmpInst.addOperand(MCOperand::createImm(N));
904     TmpInst.addOperand(MCOperand::createImm(0));
905     TmpInst.addOperand(MCOperand::createImm(31 - N));
906     Inst = TmpInst;
907     break;
908   }
909   case PPC::SRWI:
910   case PPC::SRWI_rec: {
911     MCInst TmpInst;
912     int64_t N = Inst.getOperand(2).getImm();
913     TmpInst.setOpcode(Opcode == PPC::SRWI ? PPC::RLWINM : PPC::RLWINM_rec);
914     TmpInst.addOperand(Inst.getOperand(0));
915     TmpInst.addOperand(Inst.getOperand(1));
916     TmpInst.addOperand(MCOperand::createImm(32 - N));
917     TmpInst.addOperand(MCOperand::createImm(N));
918     TmpInst.addOperand(MCOperand::createImm(31));
919     Inst = TmpInst;
920     break;
921   }
922   case PPC::CLRRWI:
923   case PPC::CLRRWI_rec: {
924     MCInst TmpInst;
925     int64_t N = Inst.getOperand(2).getImm();
926     TmpInst.setOpcode(Opcode == PPC::CLRRWI ? PPC::RLWINM : PPC::RLWINM_rec);
927     TmpInst.addOperand(Inst.getOperand(0));
928     TmpInst.addOperand(Inst.getOperand(1));
929     TmpInst.addOperand(MCOperand::createImm(0));
930     TmpInst.addOperand(MCOperand::createImm(0));
931     TmpInst.addOperand(MCOperand::createImm(31 - N));
932     Inst = TmpInst;
933     break;
934   }
935   case PPC::CLRLSLWI:
936   case PPC::CLRLSLWI_rec: {
937     MCInst TmpInst;
938     int64_t B = Inst.getOperand(2).getImm();
939     int64_t N = Inst.getOperand(3).getImm();
940     TmpInst.setOpcode(Opcode == PPC::CLRLSLWI ? PPC::RLWINM : PPC::RLWINM_rec);
941     TmpInst.addOperand(Inst.getOperand(0));
942     TmpInst.addOperand(Inst.getOperand(1));
943     TmpInst.addOperand(MCOperand::createImm(N));
944     TmpInst.addOperand(MCOperand::createImm(B - N));
945     TmpInst.addOperand(MCOperand::createImm(31 - N));
946     Inst = TmpInst;
947     break;
948   }
949   case PPC::EXTLDI:
950   case PPC::EXTLDI_rec: {
951     MCInst TmpInst;
952     int64_t N = Inst.getOperand(2).getImm();
953     int64_t B = Inst.getOperand(3).getImm();
954     TmpInst.setOpcode(Opcode == PPC::EXTLDI ? PPC::RLDICR : PPC::RLDICR_rec);
955     TmpInst.addOperand(Inst.getOperand(0));
956     TmpInst.addOperand(Inst.getOperand(1));
957     TmpInst.addOperand(MCOperand::createImm(B));
958     TmpInst.addOperand(MCOperand::createImm(N - 1));
959     Inst = TmpInst;
960     break;
961   }
962   case PPC::EXTRDI:
963   case PPC::EXTRDI_rec: {
964     MCInst TmpInst;
965     int64_t N = Inst.getOperand(2).getImm();
966     int64_t B = Inst.getOperand(3).getImm();
967     TmpInst.setOpcode(Opcode == PPC::EXTRDI ? PPC::RLDICL : PPC::RLDICL_rec);
968     TmpInst.addOperand(Inst.getOperand(0));
969     TmpInst.addOperand(Inst.getOperand(1));
970     TmpInst.addOperand(MCOperand::createImm(B + N));
971     TmpInst.addOperand(MCOperand::createImm(64 - N));
972     Inst = TmpInst;
973     break;
974   }
975   case PPC::INSRDI:
976   case PPC::INSRDI_rec: {
977     MCInst TmpInst;
978     int64_t N = Inst.getOperand(2).getImm();
979     int64_t B = Inst.getOperand(3).getImm();
980     TmpInst.setOpcode(Opcode == PPC::INSRDI ? PPC::RLDIMI : PPC::RLDIMI_rec);
981     TmpInst.addOperand(Inst.getOperand(0));
982     TmpInst.addOperand(Inst.getOperand(0));
983     TmpInst.addOperand(Inst.getOperand(1));
984     TmpInst.addOperand(MCOperand::createImm(64 - (B + N)));
985     TmpInst.addOperand(MCOperand::createImm(B));
986     Inst = TmpInst;
987     break;
988   }
989   case PPC::ROTRDI:
990   case PPC::ROTRDI_rec: {
991     MCInst TmpInst;
992     int64_t N = Inst.getOperand(2).getImm();
993     TmpInst.setOpcode(Opcode == PPC::ROTRDI ? PPC::RLDICL : PPC::RLDICL_rec);
994     TmpInst.addOperand(Inst.getOperand(0));
995     TmpInst.addOperand(Inst.getOperand(1));
996     TmpInst.addOperand(MCOperand::createImm(64 - N));
997     TmpInst.addOperand(MCOperand::createImm(0));
998     Inst = TmpInst;
999     break;
1000   }
1001   case PPC::SLDI:
1002   case PPC::SLDI_rec: {
1003     MCInst TmpInst;
1004     int64_t N = Inst.getOperand(2).getImm();
1005     TmpInst.setOpcode(Opcode == PPC::SLDI ? PPC::RLDICR : PPC::RLDICR_rec);
1006     TmpInst.addOperand(Inst.getOperand(0));
1007     TmpInst.addOperand(Inst.getOperand(1));
1008     TmpInst.addOperand(MCOperand::createImm(N));
1009     TmpInst.addOperand(MCOperand::createImm(63 - N));
1010     Inst = TmpInst;
1011     break;
1012   }
1013   case PPC::SUBPCIS: {
1014     MCInst TmpInst;
1015     int64_t N = Inst.getOperand(1).getImm();
1016     TmpInst.setOpcode(PPC::ADDPCIS);
1017     TmpInst.addOperand(Inst.getOperand(0));
1018     TmpInst.addOperand(MCOperand::createImm(-N));
1019     Inst = TmpInst;
1020     break;
1021   }
1022   case PPC::SRDI:
1023   case PPC::SRDI_rec: {
1024     MCInst TmpInst;
1025     int64_t N = Inst.getOperand(2).getImm();
1026     TmpInst.setOpcode(Opcode == PPC::SRDI ? PPC::RLDICL : PPC::RLDICL_rec);
1027     TmpInst.addOperand(Inst.getOperand(0));
1028     TmpInst.addOperand(Inst.getOperand(1));
1029     TmpInst.addOperand(MCOperand::createImm(64 - N));
1030     TmpInst.addOperand(MCOperand::createImm(N));
1031     Inst = TmpInst;
1032     break;
1033   }
1034   case PPC::CLRRDI:
1035   case PPC::CLRRDI_rec: {
1036     MCInst TmpInst;
1037     int64_t N = Inst.getOperand(2).getImm();
1038     TmpInst.setOpcode(Opcode == PPC::CLRRDI ? PPC::RLDICR : PPC::RLDICR_rec);
1039     TmpInst.addOperand(Inst.getOperand(0));
1040     TmpInst.addOperand(Inst.getOperand(1));
1041     TmpInst.addOperand(MCOperand::createImm(0));
1042     TmpInst.addOperand(MCOperand::createImm(63 - N));
1043     Inst = TmpInst;
1044     break;
1045   }
1046   case PPC::CLRLSLDI:
1047   case PPC::CLRLSLDI_rec: {
1048     MCInst TmpInst;
1049     int64_t B = Inst.getOperand(2).getImm();
1050     int64_t N = Inst.getOperand(3).getImm();
1051     TmpInst.setOpcode(Opcode == PPC::CLRLSLDI ? PPC::RLDIC : PPC::RLDIC_rec);
1052     TmpInst.addOperand(Inst.getOperand(0));
1053     TmpInst.addOperand(Inst.getOperand(1));
1054     TmpInst.addOperand(MCOperand::createImm(N));
1055     TmpInst.addOperand(MCOperand::createImm(B - N));
1056     Inst = TmpInst;
1057     break;
1058   }
1059   case PPC::RLWINMbm:
1060   case PPC::RLWINMbm_rec: {
1061     unsigned MB, ME;
1062     int64_t BM = Inst.getOperand(3).getImm();
1063     if (!isRunOfOnes(BM, MB, ME))
1064       break;
1065 
1066     MCInst TmpInst;
1067     TmpInst.setOpcode(Opcode == PPC::RLWINMbm ? PPC::RLWINM : PPC::RLWINM_rec);
1068     TmpInst.addOperand(Inst.getOperand(0));
1069     TmpInst.addOperand(Inst.getOperand(1));
1070     TmpInst.addOperand(Inst.getOperand(2));
1071     TmpInst.addOperand(MCOperand::createImm(MB));
1072     TmpInst.addOperand(MCOperand::createImm(ME));
1073     Inst = TmpInst;
1074     break;
1075   }
1076   case PPC::RLWIMIbm:
1077   case PPC::RLWIMIbm_rec: {
1078     unsigned MB, ME;
1079     int64_t BM = Inst.getOperand(3).getImm();
1080     if (!isRunOfOnes(BM, MB, ME))
1081       break;
1082 
1083     MCInst TmpInst;
1084     TmpInst.setOpcode(Opcode == PPC::RLWIMIbm ? PPC::RLWIMI : PPC::RLWIMI_rec);
1085     TmpInst.addOperand(Inst.getOperand(0));
1086     TmpInst.addOperand(Inst.getOperand(0)); // The tied operand.
1087     TmpInst.addOperand(Inst.getOperand(1));
1088     TmpInst.addOperand(Inst.getOperand(2));
1089     TmpInst.addOperand(MCOperand::createImm(MB));
1090     TmpInst.addOperand(MCOperand::createImm(ME));
1091     Inst = TmpInst;
1092     break;
1093   }
1094   case PPC::RLWNMbm:
1095   case PPC::RLWNMbm_rec: {
1096     unsigned MB, ME;
1097     int64_t BM = Inst.getOperand(3).getImm();
1098     if (!isRunOfOnes(BM, MB, ME))
1099       break;
1100 
1101     MCInst TmpInst;
1102     TmpInst.setOpcode(Opcode == PPC::RLWNMbm ? PPC::RLWNM : PPC::RLWNM_rec);
1103     TmpInst.addOperand(Inst.getOperand(0));
1104     TmpInst.addOperand(Inst.getOperand(1));
1105     TmpInst.addOperand(Inst.getOperand(2));
1106     TmpInst.addOperand(MCOperand::createImm(MB));
1107     TmpInst.addOperand(MCOperand::createImm(ME));
1108     Inst = TmpInst;
1109     break;
1110   }
1111   case PPC::MFTB: {
1112     if (getSTI().getFeatureBits()[PPC::FeatureMFTB]) {
1113       assert(Inst.getNumOperands() == 2 && "Expecting two operands");
1114       Inst.setOpcode(PPC::MFSPR);
1115     }
1116     break;
1117   }
1118   case PPC::CP_COPYx:
1119   case PPC::CP_COPY_FIRST: {
1120     MCInst TmpInst;
1121     TmpInst.setOpcode(PPC::CP_COPY);
1122     TmpInst.addOperand(Inst.getOperand(0));
1123     TmpInst.addOperand(Inst.getOperand(1));
1124     TmpInst.addOperand(MCOperand::createImm(Opcode == PPC::CP_COPYx ? 0 : 1));
1125 
1126     Inst = TmpInst;
1127     break;
1128   }
1129   case PPC::CP_PASTEx :
1130   case PPC::CP_PASTE_LAST: {
1131     MCInst TmpInst;
1132     TmpInst.setOpcode(Opcode == PPC::CP_PASTEx ? PPC::CP_PASTE
1133                                                : PPC::CP_PASTE_rec);
1134     TmpInst.addOperand(Inst.getOperand(0));
1135     TmpInst.addOperand(Inst.getOperand(1));
1136     TmpInst.addOperand(MCOperand::createImm(Opcode == PPC::CP_PASTEx ? 0 : 1));
1137 
1138     Inst = TmpInst;
1139     break;
1140   }
1141   }
1142 }
1143 
1144 static std::string PPCMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
1145                                          unsigned VariantID = 0);
1146 
1147 bool PPCAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1148                                            OperandVector &Operands,
1149                                            MCStreamer &Out, uint64_t &ErrorInfo,
1150                                            bool MatchingInlineAsm) {
1151   MCInst Inst;
1152 
1153   switch (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm)) {
1154   case Match_Success:
1155     // Post-process instructions (typically extended mnemonics)
1156     ProcessInstruction(Inst, Operands);
1157     Inst.setLoc(IDLoc);
1158     Out.emitInstruction(Inst, getSTI());
1159     return false;
1160   case Match_MissingFeature:
1161     return Error(IDLoc, "instruction use requires an option to be enabled");
1162   case Match_MnemonicFail: {
1163     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
1164     std::string Suggestion = PPCMnemonicSpellCheck(
1165         ((PPCOperand &)*Operands[0]).getToken(), FBS);
1166     return Error(IDLoc, "invalid instruction" + Suggestion,
1167                  ((PPCOperand &)*Operands[0]).getLocRange());
1168   }
1169   case Match_InvalidOperand: {
1170     SMLoc ErrorLoc = IDLoc;
1171     if (ErrorInfo != ~0ULL) {
1172       if (ErrorInfo >= Operands.size())
1173         return Error(IDLoc, "too few operands for instruction");
1174 
1175       ErrorLoc = ((PPCOperand &)*Operands[ErrorInfo]).getStartLoc();
1176       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1177     }
1178 
1179     return Error(ErrorLoc, "invalid operand for instruction");
1180   }
1181   }
1182 
1183   llvm_unreachable("Implement any new match types added!");
1184 }
1185 
1186 bool PPCAsmParser::MatchRegisterName(unsigned &RegNo, int64_t &IntVal) {
1187   if (getParser().getTok().is(AsmToken::Identifier)) {
1188     StringRef Name = getParser().getTok().getString();
1189     if (Name.equals_lower("lr")) {
1190       RegNo = isPPC64()? PPC::LR8 : PPC::LR;
1191       IntVal = 8;
1192     } else if (Name.equals_lower("ctr")) {
1193       RegNo = isPPC64()? PPC::CTR8 : PPC::CTR;
1194       IntVal = 9;
1195     } else if (Name.equals_lower("vrsave")) {
1196       RegNo = PPC::VRSAVE;
1197       IntVal = 256;
1198     } else if (Name.startswith_lower("r") &&
1199                !Name.substr(1).getAsInteger(10, IntVal) && IntVal < 32) {
1200       RegNo = isPPC64()? XRegs[IntVal] : RRegs[IntVal];
1201     } else if (Name.startswith_lower("f") &&
1202                !Name.substr(1).getAsInteger(10, IntVal) && IntVal < 32) {
1203       RegNo = FRegs[IntVal];
1204     } else if (Name.startswith_lower("vs") &&
1205                !Name.substr(2).getAsInteger(10, IntVal) && IntVal < 64) {
1206       RegNo = VSRegs[IntVal];
1207     } else if (Name.startswith_lower("v") &&
1208                !Name.substr(1).getAsInteger(10, IntVal) && IntVal < 32) {
1209       RegNo = VRegs[IntVal];
1210     } else if (Name.startswith_lower("q") &&
1211                !Name.substr(1).getAsInteger(10, IntVal) && IntVal < 32) {
1212       RegNo = QFRegs[IntVal];
1213     } else if (Name.startswith_lower("cr") &&
1214                !Name.substr(2).getAsInteger(10, IntVal) && IntVal < 8) {
1215       RegNo = CRRegs[IntVal];
1216     } else
1217       return true;
1218     getParser().Lex();
1219     return false;
1220   }
1221   return true;
1222 }
1223 
1224 bool PPCAsmParser::
1225 ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) {
1226   if (tryParseRegister(RegNo, StartLoc, EndLoc) != MatchOperand_Success)
1227     return TokError("invalid register name");
1228   return false;
1229 }
1230 
1231 OperandMatchResultTy PPCAsmParser::tryParseRegister(unsigned &RegNo,
1232                                                     SMLoc &StartLoc,
1233                                                     SMLoc &EndLoc) {
1234   const AsmToken &Tok = getParser().getTok();
1235   StartLoc = Tok.getLoc();
1236   EndLoc = Tok.getEndLoc();
1237   RegNo = 0;
1238   int64_t IntVal;
1239   if (MatchRegisterName(RegNo, IntVal))
1240     return MatchOperand_NoMatch;
1241   return MatchOperand_Success;
1242 }
1243 
1244 /// Extract \code @l/@ha \endcode modifier from expression.  Recursively scan
1245 /// the expression and check for VK_PPC_LO/HI/HA
1246 /// symbol variants.  If all symbols with modifier use the same
1247 /// variant, return the corresponding PPCMCExpr::VariantKind,
1248 /// and a modified expression using the default symbol variant.
1249 /// Otherwise, return NULL.
1250 const MCExpr *PPCAsmParser::
1251 ExtractModifierFromExpr(const MCExpr *E,
1252                         PPCMCExpr::VariantKind &Variant) {
1253   MCContext &Context = getParser().getContext();
1254   Variant = PPCMCExpr::VK_PPC_None;
1255 
1256   switch (E->getKind()) {
1257   case MCExpr::Target:
1258   case MCExpr::Constant:
1259     return nullptr;
1260 
1261   case MCExpr::SymbolRef: {
1262     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1263 
1264     switch (SRE->getKind()) {
1265     case MCSymbolRefExpr::VK_PPC_LO:
1266       Variant = PPCMCExpr::VK_PPC_LO;
1267       break;
1268     case MCSymbolRefExpr::VK_PPC_HI:
1269       Variant = PPCMCExpr::VK_PPC_HI;
1270       break;
1271     case MCSymbolRefExpr::VK_PPC_HA:
1272       Variant = PPCMCExpr::VK_PPC_HA;
1273       break;
1274     case MCSymbolRefExpr::VK_PPC_HIGH:
1275       Variant = PPCMCExpr::VK_PPC_HIGH;
1276       break;
1277     case MCSymbolRefExpr::VK_PPC_HIGHA:
1278       Variant = PPCMCExpr::VK_PPC_HIGHA;
1279       break;
1280     case MCSymbolRefExpr::VK_PPC_HIGHER:
1281       Variant = PPCMCExpr::VK_PPC_HIGHER;
1282       break;
1283     case MCSymbolRefExpr::VK_PPC_HIGHERA:
1284       Variant = PPCMCExpr::VK_PPC_HIGHERA;
1285       break;
1286     case MCSymbolRefExpr::VK_PPC_HIGHEST:
1287       Variant = PPCMCExpr::VK_PPC_HIGHEST;
1288       break;
1289     case MCSymbolRefExpr::VK_PPC_HIGHESTA:
1290       Variant = PPCMCExpr::VK_PPC_HIGHESTA;
1291       break;
1292     default:
1293       return nullptr;
1294     }
1295 
1296     return MCSymbolRefExpr::create(&SRE->getSymbol(), Context);
1297   }
1298 
1299   case MCExpr::Unary: {
1300     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1301     const MCExpr *Sub = ExtractModifierFromExpr(UE->getSubExpr(), Variant);
1302     if (!Sub)
1303       return nullptr;
1304     return MCUnaryExpr::create(UE->getOpcode(), Sub, Context);
1305   }
1306 
1307   case MCExpr::Binary: {
1308     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1309     PPCMCExpr::VariantKind LHSVariant, RHSVariant;
1310     const MCExpr *LHS = ExtractModifierFromExpr(BE->getLHS(), LHSVariant);
1311     const MCExpr *RHS = ExtractModifierFromExpr(BE->getRHS(), RHSVariant);
1312 
1313     if (!LHS && !RHS)
1314       return nullptr;
1315 
1316     if (!LHS) LHS = BE->getLHS();
1317     if (!RHS) RHS = BE->getRHS();
1318 
1319     if (LHSVariant == PPCMCExpr::VK_PPC_None)
1320       Variant = RHSVariant;
1321     else if (RHSVariant == PPCMCExpr::VK_PPC_None)
1322       Variant = LHSVariant;
1323     else if (LHSVariant == RHSVariant)
1324       Variant = LHSVariant;
1325     else
1326       return nullptr;
1327 
1328     return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, Context);
1329   }
1330   }
1331 
1332   llvm_unreachable("Invalid expression kind!");
1333 }
1334 
1335 /// Find all VK_TLSGD/VK_TLSLD symbol references in expression and replace
1336 /// them by VK_PPC_TLSGD/VK_PPC_TLSLD.  This is necessary to avoid having
1337 /// _GLOBAL_OFFSET_TABLE_ created via ELFObjectWriter::RelocNeedsGOT.
1338 /// FIXME: This is a hack.
1339 const MCExpr *PPCAsmParser::
1340 FixupVariantKind(const MCExpr *E) {
1341   MCContext &Context = getParser().getContext();
1342 
1343   switch (E->getKind()) {
1344   case MCExpr::Target:
1345   case MCExpr::Constant:
1346     return E;
1347 
1348   case MCExpr::SymbolRef: {
1349     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1350     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1351 
1352     switch (SRE->getKind()) {
1353     case MCSymbolRefExpr::VK_TLSGD:
1354       Variant = MCSymbolRefExpr::VK_PPC_TLSGD;
1355       break;
1356     case MCSymbolRefExpr::VK_TLSLD:
1357       Variant = MCSymbolRefExpr::VK_PPC_TLSLD;
1358       break;
1359     default:
1360       return E;
1361     }
1362     return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, Context);
1363   }
1364 
1365   case MCExpr::Unary: {
1366     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1367     const MCExpr *Sub = FixupVariantKind(UE->getSubExpr());
1368     if (Sub == UE->getSubExpr())
1369       return E;
1370     return MCUnaryExpr::create(UE->getOpcode(), Sub, Context);
1371   }
1372 
1373   case MCExpr::Binary: {
1374     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1375     const MCExpr *LHS = FixupVariantKind(BE->getLHS());
1376     const MCExpr *RHS = FixupVariantKind(BE->getRHS());
1377     if (LHS == BE->getLHS() && RHS == BE->getRHS())
1378       return E;
1379     return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, Context);
1380   }
1381   }
1382 
1383   llvm_unreachable("Invalid expression kind!");
1384 }
1385 
1386 /// ParseExpression.  This differs from the default "parseExpression" in that
1387 /// it handles modifiers.
1388 bool PPCAsmParser::
1389 ParseExpression(const MCExpr *&EVal) {
1390 
1391   if (isDarwin())
1392     return ParseDarwinExpression(EVal);
1393 
1394   // (ELF Platforms)
1395   // Handle \code @l/@ha \endcode
1396   if (getParser().parseExpression(EVal))
1397     return true;
1398 
1399   EVal = FixupVariantKind(EVal);
1400 
1401   PPCMCExpr::VariantKind Variant;
1402   const MCExpr *E = ExtractModifierFromExpr(EVal, Variant);
1403   if (E)
1404     EVal = PPCMCExpr::create(Variant, E, getParser().getContext());
1405 
1406   return false;
1407 }
1408 
1409 /// ParseDarwinExpression.  (MachO Platforms)
1410 /// This differs from the default "parseExpression" in that it handles detection
1411 /// of the \code hi16(), ha16() and lo16() \endcode modifiers.  At present,
1412 /// parseExpression() doesn't recognise the modifiers when in the Darwin/MachO
1413 /// syntax form so it is done here.  TODO: Determine if there is merit in
1414 /// arranging for this to be done at a higher level.
1415 bool PPCAsmParser::
1416 ParseDarwinExpression(const MCExpr *&EVal) {
1417   MCAsmParser &Parser = getParser();
1418   PPCMCExpr::VariantKind Variant = PPCMCExpr::VK_PPC_None;
1419   switch (getLexer().getKind()) {
1420   default:
1421     break;
1422   case AsmToken::Identifier:
1423     // Compiler-generated Darwin identifiers begin with L,l,_ or "; thus
1424     // something starting with any other char should be part of the
1425     // asm syntax.  If handwritten asm includes an identifier like lo16,
1426     // then all bets are off - but no-one would do that, right?
1427     StringRef poss = Parser.getTok().getString();
1428     if (poss.equals_lower("lo16")) {
1429       Variant = PPCMCExpr::VK_PPC_LO;
1430     } else if (poss.equals_lower("hi16")) {
1431       Variant = PPCMCExpr::VK_PPC_HI;
1432     } else if (poss.equals_lower("ha16")) {
1433       Variant = PPCMCExpr::VK_PPC_HA;
1434     }
1435     if (Variant != PPCMCExpr::VK_PPC_None) {
1436       Parser.Lex(); // Eat the xx16
1437       if (getLexer().isNot(AsmToken::LParen))
1438         return Error(Parser.getTok().getLoc(), "expected '('");
1439       Parser.Lex(); // Eat the '('
1440     }
1441     break;
1442   }
1443 
1444   if (getParser().parseExpression(EVal))
1445     return true;
1446 
1447   if (Variant != PPCMCExpr::VK_PPC_None) {
1448     if (getLexer().isNot(AsmToken::RParen))
1449       return Error(Parser.getTok().getLoc(), "expected ')'");
1450     Parser.Lex(); // Eat the ')'
1451     EVal = PPCMCExpr::create(Variant, EVal, getParser().getContext());
1452   }
1453   return false;
1454 }
1455 
1456 /// ParseOperand
1457 /// This handles registers in the form 'NN', '%rNN' for ELF platforms and
1458 /// rNN for MachO.
1459 bool PPCAsmParser::ParseOperand(OperandVector &Operands) {
1460   MCAsmParser &Parser = getParser();
1461   SMLoc S = Parser.getTok().getLoc();
1462   SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1463   const MCExpr *EVal;
1464 
1465   // Attempt to parse the next token as an immediate
1466   switch (getLexer().getKind()) {
1467   // Special handling for register names.  These are interpreted
1468   // as immediates corresponding to the register number.
1469   case AsmToken::Percent:
1470     Parser.Lex(); // Eat the '%'.
1471     unsigned RegNo;
1472     int64_t IntVal;
1473     if (MatchRegisterName(RegNo, IntVal))
1474       return Error(S, "invalid register name");
1475 
1476     Operands.push_back(PPCOperand::CreateImm(IntVal, S, E, isPPC64()));
1477     return false;
1478 
1479   case AsmToken::Identifier:
1480   case AsmToken::LParen:
1481   case AsmToken::Plus:
1482   case AsmToken::Minus:
1483   case AsmToken::Integer:
1484   case AsmToken::Dot:
1485   case AsmToken::Dollar:
1486   case AsmToken::Exclaim:
1487   case AsmToken::Tilde:
1488     // Note that non-register-name identifiers from the compiler will begin
1489     // with '_', 'L'/'l' or '"'.  Of course, handwritten asm could include
1490     // identifiers like r31foo - so we fall through in the event that parsing
1491     // a register name fails.
1492     if (isDarwin()) {
1493       unsigned RegNo;
1494       int64_t IntVal;
1495       if (!MatchRegisterName(RegNo, IntVal)) {
1496         Operands.push_back(PPCOperand::CreateImm(IntVal, S, E, isPPC64()));
1497         return false;
1498       }
1499     }
1500     // All other expressions
1501 
1502     if (!ParseExpression(EVal))
1503       break;
1504     // Fall-through
1505     LLVM_FALLTHROUGH;
1506   default:
1507     return Error(S, "unknown operand");
1508   }
1509 
1510   // Push the parsed operand into the list of operands
1511   Operands.push_back(PPCOperand::CreateFromMCExpr(EVal, S, E, isPPC64()));
1512 
1513   // Check whether this is a TLS call expression
1514   bool TLSCall = false;
1515   if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(EVal))
1516     TLSCall = Ref->getSymbol().getName() == "__tls_get_addr";
1517 
1518   if (TLSCall && getLexer().is(AsmToken::LParen)) {
1519     const MCExpr *TLSSym;
1520 
1521     Parser.Lex(); // Eat the '('.
1522     S = Parser.getTok().getLoc();
1523     if (ParseExpression(TLSSym))
1524       return Error(S, "invalid TLS call expression");
1525     if (getLexer().isNot(AsmToken::RParen))
1526       return Error(Parser.getTok().getLoc(), "missing ')'");
1527     E = Parser.getTok().getLoc();
1528     Parser.Lex(); // Eat the ')'.
1529 
1530     Operands.push_back(PPCOperand::CreateFromMCExpr(TLSSym, S, E, isPPC64()));
1531   }
1532 
1533   // Otherwise, check for D-form memory operands
1534   if (!TLSCall && getLexer().is(AsmToken::LParen)) {
1535     Parser.Lex(); // Eat the '('.
1536     S = Parser.getTok().getLoc();
1537 
1538     int64_t IntVal;
1539     switch (getLexer().getKind()) {
1540     case AsmToken::Percent:
1541       Parser.Lex(); // Eat the '%'.
1542       unsigned RegNo;
1543       if (MatchRegisterName(RegNo, IntVal))
1544         return Error(S, "invalid register name");
1545       break;
1546 
1547     case AsmToken::Integer:
1548       if (isDarwin())
1549         return Error(S, "unexpected integer value");
1550       else if (getParser().parseAbsoluteExpression(IntVal) || IntVal < 0 ||
1551                IntVal > 31)
1552         return Error(S, "invalid register number");
1553       break;
1554    case AsmToken::Identifier:
1555     if (isDarwin()) {
1556       unsigned RegNo;
1557       if (!MatchRegisterName(RegNo, IntVal)) {
1558         break;
1559       }
1560     }
1561     LLVM_FALLTHROUGH;
1562 
1563     default:
1564       return Error(S, "invalid memory operand");
1565     }
1566 
1567     E = Parser.getTok().getLoc();
1568     if (parseToken(AsmToken::RParen, "missing ')'"))
1569       return true;
1570     Operands.push_back(PPCOperand::CreateImm(IntVal, S, E, isPPC64()));
1571   }
1572 
1573   return false;
1574 }
1575 
1576 /// Parse an instruction mnemonic followed by its operands.
1577 bool PPCAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
1578                                     SMLoc NameLoc, OperandVector &Operands) {
1579   // The first operand is the token for the instruction name.
1580   // If the next character is a '+' or '-', we need to add it to the
1581   // instruction name, to match what TableGen is doing.
1582   std::string NewOpcode;
1583   if (parseOptionalToken(AsmToken::Plus)) {
1584     NewOpcode = std::string(Name);
1585     NewOpcode += '+';
1586     Name = NewOpcode;
1587   }
1588   if (parseOptionalToken(AsmToken::Minus)) {
1589     NewOpcode = std::string(Name);
1590     NewOpcode += '-';
1591     Name = NewOpcode;
1592   }
1593   // If the instruction ends in a '.', we need to create a separate
1594   // token for it, to match what TableGen is doing.
1595   size_t Dot = Name.find('.');
1596   StringRef Mnemonic = Name.slice(0, Dot);
1597   if (!NewOpcode.empty()) // Underlying memory for Name is volatile.
1598     Operands.push_back(
1599         PPCOperand::CreateTokenWithStringCopy(Mnemonic, NameLoc, isPPC64()));
1600   else
1601     Operands.push_back(PPCOperand::CreateToken(Mnemonic, NameLoc, isPPC64()));
1602   if (Dot != StringRef::npos) {
1603     SMLoc DotLoc = SMLoc::getFromPointer(NameLoc.getPointer() + Dot);
1604     StringRef DotStr = Name.slice(Dot, StringRef::npos);
1605     if (!NewOpcode.empty()) // Underlying memory for Name is volatile.
1606       Operands.push_back(
1607           PPCOperand::CreateTokenWithStringCopy(DotStr, DotLoc, isPPC64()));
1608     else
1609       Operands.push_back(PPCOperand::CreateToken(DotStr, DotLoc, isPPC64()));
1610   }
1611 
1612   // If there are no more operands then finish
1613   if (parseOptionalToken(AsmToken::EndOfStatement))
1614     return false;
1615 
1616   // Parse the first operand
1617   if (ParseOperand(Operands))
1618     return true;
1619 
1620   while (!parseOptionalToken(AsmToken::EndOfStatement)) {
1621     if (parseToken(AsmToken::Comma) || ParseOperand(Operands))
1622       return true;
1623   }
1624 
1625   // We'll now deal with an unfortunate special case: the syntax for the dcbt
1626   // and dcbtst instructions differs for server vs. embedded cores.
1627   //  The syntax for dcbt is:
1628   //    dcbt ra, rb, th [server]
1629   //    dcbt th, ra, rb [embedded]
1630   //  where th can be omitted when it is 0. dcbtst is the same. We take the
1631   //  server form to be the default, so swap the operands if we're parsing for
1632   //  an embedded core (they'll be swapped again upon printing).
1633   if (getSTI().getFeatureBits()[PPC::FeatureBookE] &&
1634       Operands.size() == 4 &&
1635       (Name == "dcbt" || Name == "dcbtst")) {
1636     std::swap(Operands[1], Operands[3]);
1637     std::swap(Operands[2], Operands[1]);
1638   }
1639 
1640   return false;
1641 }
1642 
1643 /// ParseDirective parses the PPC specific directives
1644 bool PPCAsmParser::ParseDirective(AsmToken DirectiveID) {
1645   StringRef IDVal = DirectiveID.getIdentifier();
1646   if (isDarwin()) {
1647     if (IDVal == ".machine")
1648       ParseDarwinDirectiveMachine(DirectiveID.getLoc());
1649     else
1650       return true;
1651   } else if (IDVal == ".word")
1652     ParseDirectiveWord(2, DirectiveID);
1653   else if (IDVal == ".llong")
1654     ParseDirectiveWord(8, DirectiveID);
1655   else if (IDVal == ".tc")
1656     ParseDirectiveTC(isPPC64() ? 8 : 4, DirectiveID);
1657   else if (IDVal == ".machine")
1658     ParseDirectiveMachine(DirectiveID.getLoc());
1659   else if (IDVal == ".abiversion")
1660     ParseDirectiveAbiVersion(DirectiveID.getLoc());
1661   else if (IDVal == ".localentry")
1662     ParseDirectiveLocalEntry(DirectiveID.getLoc());
1663   else
1664     return true;
1665   return false;
1666 }
1667 
1668 /// ParseDirectiveWord
1669 ///  ::= .word [ expression (, expression)* ]
1670 bool PPCAsmParser::ParseDirectiveWord(unsigned Size, AsmToken ID) {
1671   auto parseOp = [&]() -> bool {
1672     const MCExpr *Value;
1673     SMLoc ExprLoc = getParser().getTok().getLoc();
1674     if (getParser().parseExpression(Value))
1675       return true;
1676     if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) {
1677       assert(Size <= 8 && "Invalid size");
1678       uint64_t IntValue = MCE->getValue();
1679       if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1680         return Error(ExprLoc, "literal value out of range for '" +
1681                                   ID.getIdentifier() + "' directive");
1682       getStreamer().emitIntValue(IntValue, Size);
1683     } else
1684       getStreamer().emitValue(Value, Size, ExprLoc);
1685     return false;
1686   };
1687 
1688   if (parseMany(parseOp))
1689     return addErrorSuffix(" in '" + ID.getIdentifier() + "' directive");
1690   return false;
1691 }
1692 
1693 /// ParseDirectiveTC
1694 ///  ::= .tc [ symbol (, expression)* ]
1695 bool PPCAsmParser::ParseDirectiveTC(unsigned Size, AsmToken ID) {
1696   MCAsmParser &Parser = getParser();
1697   // Skip TC symbol, which is only used with XCOFF.
1698   while (getLexer().isNot(AsmToken::EndOfStatement)
1699          && getLexer().isNot(AsmToken::Comma))
1700     Parser.Lex();
1701   if (parseToken(AsmToken::Comma))
1702     return addErrorSuffix(" in '.tc' directive");
1703 
1704   // Align to word size.
1705   getParser().getStreamer().emitValueToAlignment(Size);
1706 
1707   // Emit expressions.
1708   return ParseDirectiveWord(Size, ID);
1709 }
1710 
1711 /// ParseDirectiveMachine (ELF platforms)
1712 ///  ::= .machine [ cpu | "push" | "pop" ]
1713 bool PPCAsmParser::ParseDirectiveMachine(SMLoc L) {
1714   MCAsmParser &Parser = getParser();
1715   if (Parser.getTok().isNot(AsmToken::Identifier) &&
1716       Parser.getTok().isNot(AsmToken::String))
1717     return Error(L, "unexpected token in '.machine' directive");
1718 
1719   StringRef CPU = Parser.getTok().getIdentifier();
1720 
1721   // FIXME: Right now, the parser always allows any available
1722   // instruction, so the .machine directive is not useful.
1723   // Implement ".machine any" (by doing nothing) for the benefit
1724   // of existing assembler code.  Likewise, we can then implement
1725   // ".machine push" and ".machine pop" as no-op.
1726   if (CPU != "any" && CPU != "push" && CPU != "pop")
1727     return TokError("unrecognized machine type");
1728 
1729   Parser.Lex();
1730 
1731   if (parseToken(AsmToken::EndOfStatement))
1732     return addErrorSuffix(" in '.machine' directive");
1733 
1734   PPCTargetStreamer *TStreamer = static_cast<PPCTargetStreamer *>(
1735       getParser().getStreamer().getTargetStreamer());
1736   if (TStreamer != nullptr)
1737     TStreamer->emitMachine(CPU);
1738 
1739   return false;
1740 }
1741 
1742 /// ParseDarwinDirectiveMachine (Mach-o platforms)
1743 ///  ::= .machine cpu-identifier
1744 bool PPCAsmParser::ParseDarwinDirectiveMachine(SMLoc L) {
1745   MCAsmParser &Parser = getParser();
1746   if (Parser.getTok().isNot(AsmToken::Identifier) &&
1747       Parser.getTok().isNot(AsmToken::String))
1748     return Error(L, "unexpected token in directive");
1749 
1750   StringRef CPU = Parser.getTok().getIdentifier();
1751   Parser.Lex();
1752 
1753   // FIXME: this is only the 'default' set of cpu variants.
1754   // However we don't act on this information at present, this is simply
1755   // allowing parsing to proceed with minimal sanity checking.
1756   if (check(CPU != "ppc7400" && CPU != "ppc" && CPU != "ppc64", L,
1757             "unrecognized cpu type") ||
1758       check(isPPC64() && (CPU == "ppc7400" || CPU == "ppc"), L,
1759             "wrong cpu type specified for 64bit") ||
1760       check(!isPPC64() && CPU == "ppc64", L,
1761             "wrong cpu type specified for 32bit") ||
1762       parseToken(AsmToken::EndOfStatement))
1763     return addErrorSuffix(" in '.machine' directive");
1764   return false;
1765 }
1766 
1767 /// ParseDirectiveAbiVersion
1768 ///  ::= .abiversion constant-expression
1769 bool PPCAsmParser::ParseDirectiveAbiVersion(SMLoc L) {
1770   int64_t AbiVersion;
1771   if (check(getParser().parseAbsoluteExpression(AbiVersion), L,
1772             "expected constant expression") ||
1773       parseToken(AsmToken::EndOfStatement))
1774     return addErrorSuffix(" in '.abiversion' directive");
1775 
1776   PPCTargetStreamer *TStreamer = static_cast<PPCTargetStreamer *>(
1777       getParser().getStreamer().getTargetStreamer());
1778   if (TStreamer != nullptr)
1779     TStreamer->emitAbiVersion(AbiVersion);
1780 
1781   return false;
1782 }
1783 
1784 /// ParseDirectiveLocalEntry
1785 ///  ::= .localentry symbol, expression
1786 bool PPCAsmParser::ParseDirectiveLocalEntry(SMLoc L) {
1787   StringRef Name;
1788   if (getParser().parseIdentifier(Name))
1789     return Error(L, "expected identifier in '.localentry' directive");
1790 
1791   MCSymbolELF *Sym = cast<MCSymbolELF>(getContext().getOrCreateSymbol(Name));
1792   const MCExpr *Expr;
1793 
1794   if (parseToken(AsmToken::Comma) ||
1795       check(getParser().parseExpression(Expr), L, "expected expression") ||
1796       parseToken(AsmToken::EndOfStatement))
1797     return addErrorSuffix(" in '.localentry' directive");
1798 
1799   PPCTargetStreamer *TStreamer = static_cast<PPCTargetStreamer *>(
1800       getParser().getStreamer().getTargetStreamer());
1801   if (TStreamer != nullptr)
1802     TStreamer->emitLocalEntry(Sym, Expr);
1803 
1804   return false;
1805 }
1806 
1807 
1808 
1809 /// Force static initialization.
1810 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmParser() {
1811   RegisterMCAsmParser<PPCAsmParser> A(getThePPC32Target());
1812   RegisterMCAsmParser<PPCAsmParser> B(getThePPC64Target());
1813   RegisterMCAsmParser<PPCAsmParser> C(getThePPC64LETarget());
1814 }
1815 
1816 #define GET_REGISTER_MATCHER
1817 #define GET_MATCHER_IMPLEMENTATION
1818 #define GET_MNEMONIC_SPELL_CHECKER
1819 #include "PPCGenAsmMatcher.inc"
1820 
1821 // Define this matcher function after the auto-generated include so we
1822 // have the match class enum definitions.
1823 unsigned PPCAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1824                                                   unsigned Kind) {
1825   // If the kind is a token for a literal immediate, check if our asm
1826   // operand matches. This is for InstAliases which have a fixed-value
1827   // immediate in the syntax.
1828   int64_t ImmVal;
1829   switch (Kind) {
1830     case MCK_0: ImmVal = 0; break;
1831     case MCK_1: ImmVal = 1; break;
1832     case MCK_2: ImmVal = 2; break;
1833     case MCK_3: ImmVal = 3; break;
1834     case MCK_4: ImmVal = 4; break;
1835     case MCK_5: ImmVal = 5; break;
1836     case MCK_6: ImmVal = 6; break;
1837     case MCK_7: ImmVal = 7; break;
1838     default: return Match_InvalidOperand;
1839   }
1840 
1841   PPCOperand &Op = static_cast<PPCOperand &>(AsmOp);
1842   if (Op.isImm() && Op.getImm() == ImmVal)
1843     return Match_Success;
1844 
1845   return Match_InvalidOperand;
1846 }
1847 
1848 const MCExpr *
1849 PPCAsmParser::applyModifierToExpr(const MCExpr *E,
1850                                   MCSymbolRefExpr::VariantKind Variant,
1851                                   MCContext &Ctx) {
1852   switch (Variant) {
1853   case MCSymbolRefExpr::VK_PPC_LO:
1854     return PPCMCExpr::create(PPCMCExpr::VK_PPC_LO, E, Ctx);
1855   case MCSymbolRefExpr::VK_PPC_HI:
1856     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HI, E, Ctx);
1857   case MCSymbolRefExpr::VK_PPC_HA:
1858     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HA, E, Ctx);
1859   case MCSymbolRefExpr::VK_PPC_HIGH:
1860     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGH, E, Ctx);
1861   case MCSymbolRefExpr::VK_PPC_HIGHA:
1862     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHA, E, Ctx);
1863   case MCSymbolRefExpr::VK_PPC_HIGHER:
1864     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHER, E, Ctx);
1865   case MCSymbolRefExpr::VK_PPC_HIGHERA:
1866     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHERA, E, Ctx);
1867   case MCSymbolRefExpr::VK_PPC_HIGHEST:
1868     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHEST, E, Ctx);
1869   case MCSymbolRefExpr::VK_PPC_HIGHESTA:
1870     return PPCMCExpr::create(PPCMCExpr::VK_PPC_HIGHESTA, E, Ctx);
1871   default:
1872     return nullptr;
1873   }
1874 }
1875