1 //===- llvm/InlineAsm.h - Class to represent inline asm strings -*- C++ -*-===//
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 // This class represents the inline asm strings, which are Value*'s that are
10 // used as the callee operand of call instructions.  InlineAsm's are uniqued
11 // like constants, and created via InlineAsm::get(...).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_INLINEASM_H
16 #define LLVM_IR_INLINEASM_H
17 
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <cassert>
22 #include <string>
23 #include <vector>
24 
25 namespace llvm {
26 
27 class Error;
28 class FunctionType;
29 class PointerType;
30 template <class ConstantClass> class ConstantUniqueMap;
31 
32 class InlineAsm final : public Value {
33 public:
34   enum AsmDialect {
35     AD_ATT,
36     AD_Intel
37   };
38 
39 private:
40   friend struct InlineAsmKeyType;
41   friend class ConstantUniqueMap<InlineAsm>;
42 
43   std::string AsmString, Constraints;
44   FunctionType *FTy;
45   bool HasSideEffects;
46   bool IsAlignStack;
47   AsmDialect Dialect;
48   bool CanThrow;
49 
50   InlineAsm(FunctionType *Ty, const std::string &AsmString,
51             const std::string &Constraints, bool hasSideEffects,
52             bool isAlignStack, AsmDialect asmDialect, bool canThrow);
53 
54   /// When the ConstantUniqueMap merges two types and makes two InlineAsms
55   /// identical, it destroys one of them with this method.
56   void destroyConstant();
57 
58 public:
59   InlineAsm(const InlineAsm &) = delete;
60   InlineAsm &operator=(const InlineAsm &) = delete;
61 
62   /// InlineAsm::get - Return the specified uniqued inline asm string.
63   ///
64   static InlineAsm *get(FunctionType *Ty, StringRef AsmString,
65                         StringRef Constraints, bool hasSideEffects,
66                         bool isAlignStack = false,
67                         AsmDialect asmDialect = AD_ATT, bool canThrow = false);
68 
69   bool hasSideEffects() const { return HasSideEffects; }
70   bool isAlignStack() const { return IsAlignStack; }
71   AsmDialect getDialect() const { return Dialect; }
72   bool canThrow() const { return CanThrow; }
73 
74   /// getType - InlineAsm's are always pointers.
75   ///
76   PointerType *getType() const {
77     return reinterpret_cast<PointerType*>(Value::getType());
78   }
79 
80   /// getFunctionType - InlineAsm's are always pointers to functions.
81   ///
82   FunctionType *getFunctionType() const;
83 
84   const std::string &getAsmString() const { return AsmString; }
85   const std::string &getConstraintString() const { return Constraints; }
86 
87   /// This static method can be used by the parser to check to see if the
88   /// specified constraint string is legal for the type.
89   static Error verify(FunctionType *Ty, StringRef Constraints);
90 
91   // Constraint String Parsing
92   enum ConstraintPrefix {
93     isInput,            // 'x'
94     isOutput,           // '=x'
95     isClobber,          // '~x'
96     isLabel,            // '!x'
97   };
98 
99   using ConstraintCodeVector = std::vector<std::string>;
100 
101   struct SubConstraintInfo {
102     /// MatchingInput - If this is not -1, this is an output constraint where an
103     /// input constraint is required to match it (e.g. "0").  The value is the
104     /// constraint number that matches this one (for example, if this is
105     /// constraint #0 and constraint #4 has the value "0", this will be 4).
106     int MatchingInput = -1;
107 
108     /// Code - The constraint code, either the register name (in braces) or the
109     /// constraint letter/number.
110     ConstraintCodeVector Codes;
111 
112     /// Default constructor.
113     SubConstraintInfo() = default;
114   };
115 
116   using SubConstraintInfoVector = std::vector<SubConstraintInfo>;
117   struct ConstraintInfo;
118   using ConstraintInfoVector = std::vector<ConstraintInfo>;
119 
120   struct ConstraintInfo {
121     /// Type - The basic type of the constraint: input/output/clobber/label
122     ///
123     ConstraintPrefix Type = isInput;
124 
125     /// isEarlyClobber - "&": output operand writes result before inputs are all
126     /// read.  This is only ever set for an output operand.
127     bool isEarlyClobber = false;
128 
129     /// MatchingInput - If this is not -1, this is an output constraint where an
130     /// input constraint is required to match it (e.g. "0").  The value is the
131     /// constraint number that matches this one (for example, if this is
132     /// constraint #0 and constraint #4 has the value "0", this will be 4).
133     int MatchingInput = -1;
134 
135     /// hasMatchingInput - Return true if this is an output constraint that has
136     /// a matching input constraint.
137     bool hasMatchingInput() const { return MatchingInput != -1; }
138 
139     /// isCommutative - This is set to true for a constraint that is commutative
140     /// with the next operand.
141     bool isCommutative = false;
142 
143     /// isIndirect - True if this operand is an indirect operand.  This means
144     /// that the address of the source or destination is present in the call
145     /// instruction, instead of it being returned or passed in explicitly.  This
146     /// is represented with a '*' in the asm string.
147     bool isIndirect = false;
148 
149     /// Code - The constraint code, either the register name (in braces) or the
150     /// constraint letter/number.
151     ConstraintCodeVector Codes;
152 
153     /// isMultipleAlternative - '|': has multiple-alternative constraints.
154     bool isMultipleAlternative = false;
155 
156     /// multipleAlternatives - If there are multiple alternative constraints,
157     /// this array will contain them.  Otherwise it will be empty.
158     SubConstraintInfoVector multipleAlternatives;
159 
160     /// The currently selected alternative constraint index.
161     unsigned currentAlternativeIndex = 0;
162 
163     /// Default constructor.
164     ConstraintInfo() = default;
165 
166     /// Parse - Analyze the specified string (e.g. "=*&{eax}") and fill in the
167     /// fields in this structure.  If the constraint string is not understood,
168     /// return true, otherwise return false.
169     bool Parse(StringRef Str, ConstraintInfoVector &ConstraintsSoFar);
170 
171     /// selectAlternative - Point this constraint to the alternative constraint
172     /// indicated by the index.
173     void selectAlternative(unsigned index);
174 
175     /// Whether this constraint corresponds to an argument.
176     bool hasArg() const {
177       return Type == isInput || (Type == isOutput && isIndirect);
178     }
179   };
180 
181   /// ParseConstraints - Split up the constraint string into the specific
182   /// constraints and their prefixes.  If this returns an empty vector, and if
183   /// the constraint string itself isn't empty, there was an error parsing.
184   static ConstraintInfoVector ParseConstraints(StringRef ConstraintString);
185 
186   /// ParseConstraints - Parse the constraints of this inlineasm object,
187   /// returning them the same way that ParseConstraints(str) does.
188   ConstraintInfoVector ParseConstraints() const {
189     return ParseConstraints(Constraints);
190   }
191 
192   // Methods for support type inquiry through isa, cast, and dyn_cast:
193   static bool classof(const Value *V) {
194     return V->getValueID() == Value::InlineAsmVal;
195   }
196 
197   // These are helper methods for dealing with flags in the INLINEASM SDNode
198   // in the backend.
199   //
200   // The encoding of the flag word is currently:
201   //   Bits 2-0 - A Kind_* value indicating the kind of the operand.
202   //   Bits 15-3 - The number of SDNode operands associated with this inline
203   //               assembly operand.
204   //   If bit 31 is set:
205   //     Bit 30-16 - The operand number that this operand must match.
206   //                 When bits 2-0 are Kind_Mem, the Constraint_* value must be
207   //                 obtained from the flags for this operand number.
208   //   Else if bits 2-0 are Kind_Mem:
209   //     Bit 30-16 - A Constraint_* value indicating the original constraint
210   //                 code.
211   //   Else:
212   //     Bit 30-16 - The register class ID to use for the operand.
213 
214   enum : uint32_t {
215     // Fixed operands on an INLINEASM SDNode.
216     Op_InputChain = 0,
217     Op_AsmString = 1,
218     Op_MDNode = 2,
219     Op_ExtraInfo = 3,    // HasSideEffects, IsAlignStack, AsmDialect.
220     Op_FirstOperand = 4,
221 
222     // Fixed operands on an INLINEASM MachineInstr.
223     MIOp_AsmString = 0,
224     MIOp_ExtraInfo = 1,    // HasSideEffects, IsAlignStack, AsmDialect.
225     MIOp_FirstOperand = 2,
226 
227     // Interpretation of the MIOp_ExtraInfo bit field.
228     Extra_HasSideEffects = 1,
229     Extra_IsAlignStack = 2,
230     Extra_AsmDialect = 4,
231     Extra_MayLoad = 8,
232     Extra_MayStore = 16,
233     Extra_IsConvergent = 32,
234 
235     // Inline asm operands map to multiple SDNode / MachineInstr operands.
236     // The first operand is an immediate describing the asm operand, the low
237     // bits is the kind:
238     Kind_RegUse = 1,             // Input register, "r".
239     Kind_RegDef = 2,             // Output register, "=r".
240     Kind_RegDefEarlyClobber = 3, // Early-clobber output register, "=&r".
241     Kind_Clobber = 4,            // Clobbered register, "~r".
242     Kind_Imm = 5,                // Immediate.
243     Kind_Mem = 6,                // Memory operand, "m", or an address, "p".
244 
245     // Memory constraint codes.
246     // These could be tablegenerated but there's little need to do that since
247     // there's plenty of space in the encoding to support the union of all
248     // constraint codes for all targets.
249     // Addresses are included here as they need to be treated the same by the
250     // backend, the only difference is that they are not used to actaully
251     // access memory by the instruction.
252     Constraint_Unknown = 0,
253     Constraint_es,
254     Constraint_i,
255     Constraint_m,
256     Constraint_o,
257     Constraint_v,
258     Constraint_A,
259     Constraint_Q,
260     Constraint_R,
261     Constraint_S,
262     Constraint_T,
263     Constraint_Um,
264     Constraint_Un,
265     Constraint_Uq,
266     Constraint_Us,
267     Constraint_Ut,
268     Constraint_Uv,
269     Constraint_Uy,
270     Constraint_X,
271     Constraint_Z,
272     Constraint_ZC,
273     Constraint_Zy,
274 
275     // Address constraints
276     Constraint_p,
277     Constraint_ZQ,
278     Constraint_ZR,
279     Constraint_ZS,
280     Constraint_ZT,
281 
282     Constraints_Max = Constraint_ZT,
283     Constraints_ShiftAmount = 16,
284 
285     Flag_MatchingOperand = 0x80000000
286   };
287 
288   static unsigned getFlagWord(unsigned Kind, unsigned NumOps) {
289     assert(((NumOps << 3) & ~0xffff) == 0 && "Too many inline asm operands!");
290     assert(Kind >= Kind_RegUse && Kind <= Kind_Mem && "Invalid Kind");
291     return Kind | (NumOps << 3);
292   }
293 
294   static bool isRegDefKind(unsigned Flag){ return getKind(Flag) == Kind_RegDef;}
295   static bool isImmKind(unsigned Flag) { return getKind(Flag) == Kind_Imm; }
296   static bool isMemKind(unsigned Flag) { return getKind(Flag) == Kind_Mem; }
297   static bool isRegDefEarlyClobberKind(unsigned Flag) {
298     return getKind(Flag) == Kind_RegDefEarlyClobber;
299   }
300   static bool isClobberKind(unsigned Flag) {
301     return getKind(Flag) == Kind_Clobber;
302   }
303 
304   /// getFlagWordForMatchingOp - Augment an existing flag word returned by
305   /// getFlagWord with information indicating that this input operand is tied
306   /// to a previous output operand.
307   static unsigned getFlagWordForMatchingOp(unsigned InputFlag,
308                                            unsigned MatchedOperandNo) {
309     assert(MatchedOperandNo <= 0x7fff && "Too big matched operand");
310     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
311     return InputFlag | Flag_MatchingOperand | (MatchedOperandNo << 16);
312   }
313 
314   /// getFlagWordForRegClass - Augment an existing flag word returned by
315   /// getFlagWord with the required register class for the following register
316   /// operands.
317   /// A tied use operand cannot have a register class, use the register class
318   /// from the def operand instead.
319   static unsigned getFlagWordForRegClass(unsigned InputFlag, unsigned RC) {
320     // Store RC + 1, reserve the value 0 to mean 'no register class'.
321     ++RC;
322     assert(!isImmKind(InputFlag) && "Immediates cannot have a register class");
323     assert(!isMemKind(InputFlag) && "Memory operand cannot have a register class");
324     assert(RC <= 0x7fff && "Too large register class ID");
325     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
326     return InputFlag | (RC << 16);
327   }
328 
329   /// Augment an existing flag word returned by getFlagWord with the constraint
330   /// code for a memory constraint.
331   static unsigned getFlagWordForMem(unsigned InputFlag, unsigned Constraint) {
332     assert(isMemKind(InputFlag) && "InputFlag is not a memory constraint!");
333     assert(Constraint <= 0x7fff && "Too large a memory constraint ID");
334     assert(Constraint <= Constraints_Max && "Unknown constraint ID");
335     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
336     return InputFlag | (Constraint << Constraints_ShiftAmount);
337   }
338 
339   static unsigned convertMemFlagWordToMatchingFlagWord(unsigned InputFlag) {
340     assert(isMemKind(InputFlag));
341     return InputFlag & ~(0x7fff << Constraints_ShiftAmount);
342   }
343 
344   static unsigned getKind(unsigned Flags) {
345     return Flags & 7;
346   }
347 
348   static unsigned getMemoryConstraintID(unsigned Flag) {
349     assert(isMemKind(Flag));
350     return (Flag >> Constraints_ShiftAmount) & 0x7fff;
351   }
352 
353   /// getNumOperandRegisters - Extract the number of registers field from the
354   /// inline asm operand flag.
355   static unsigned getNumOperandRegisters(unsigned Flag) {
356     return (Flag & 0xffff) >> 3;
357   }
358 
359   /// isUseOperandTiedToDef - Return true if the flag of the inline asm
360   /// operand indicates it is an use operand that's matched to a def operand.
361   static bool isUseOperandTiedToDef(unsigned Flag, unsigned &Idx) {
362     if ((Flag & Flag_MatchingOperand) == 0)
363       return false;
364     Idx = (Flag & ~Flag_MatchingOperand) >> 16;
365     return true;
366   }
367 
368   /// hasRegClassConstraint - Returns true if the flag contains a register
369   /// class constraint.  Sets RC to the register class ID.
370   static bool hasRegClassConstraint(unsigned Flag, unsigned &RC) {
371     if (Flag & Flag_MatchingOperand)
372       return false;
373     unsigned High = Flag >> 16;
374     // getFlagWordForRegClass() uses 0 to mean no register class, and otherwise
375     // stores RC + 1.
376     if (!High)
377       return false;
378     RC = High - 1;
379     return true;
380   }
381 
382   static std::vector<StringRef> getExtraInfoNames(unsigned ExtraInfo) {
383     std::vector<StringRef> Result;
384     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
385       Result.push_back("sideeffect");
386     if (ExtraInfo & InlineAsm::Extra_MayLoad)
387       Result.push_back("mayload");
388     if (ExtraInfo & InlineAsm::Extra_MayStore)
389       Result.push_back("maystore");
390     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
391       Result.push_back("isconvergent");
392     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
393       Result.push_back("alignstack");
394 
395     AsmDialect Dialect =
396         InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect));
397 
398     if (Dialect == InlineAsm::AD_ATT)
399       Result.push_back("attdialect");
400     if (Dialect == InlineAsm::AD_Intel)
401       Result.push_back("inteldialect");
402 
403     return Result;
404   }
405 
406   static StringRef getKindName(unsigned Kind) {
407     switch (Kind) {
408     case InlineAsm::Kind_RegUse:
409       return "reguse";
410     case InlineAsm::Kind_RegDef:
411       return "regdef";
412     case InlineAsm::Kind_RegDefEarlyClobber:
413       return "regdef-ec";
414     case InlineAsm::Kind_Clobber:
415       return "clobber";
416     case InlineAsm::Kind_Imm:
417       return "imm";
418     case InlineAsm::Kind_Mem:
419       return "mem";
420     default:
421       llvm_unreachable("Unknown operand kind");
422     }
423   }
424 
425   static StringRef getMemConstraintName(unsigned Constraint) {
426     switch (Constraint) {
427     case InlineAsm::Constraint_es:
428       return "es";
429     case InlineAsm::Constraint_i:
430       return "i";
431     case InlineAsm::Constraint_m:
432       return "m";
433     case InlineAsm::Constraint_o:
434       return "o";
435     case InlineAsm::Constraint_v:
436       return "v";
437     case InlineAsm::Constraint_Q:
438       return "Q";
439     case InlineAsm::Constraint_R:
440       return "R";
441     case InlineAsm::Constraint_S:
442       return "S";
443     case InlineAsm::Constraint_T:
444       return "T";
445     case InlineAsm::Constraint_Um:
446       return "Um";
447     case InlineAsm::Constraint_Un:
448       return "Un";
449     case InlineAsm::Constraint_Uq:
450       return "Uq";
451     case InlineAsm::Constraint_Us:
452       return "Us";
453     case InlineAsm::Constraint_Ut:
454       return "Ut";
455     case InlineAsm::Constraint_Uv:
456       return "Uv";
457     case InlineAsm::Constraint_Uy:
458       return "Uy";
459     case InlineAsm::Constraint_X:
460       return "X";
461     case InlineAsm::Constraint_Z:
462       return "Z";
463     case InlineAsm::Constraint_ZC:
464       return "ZC";
465     case InlineAsm::Constraint_Zy:
466       return "Zy";
467     case InlineAsm::Constraint_p:
468       return "p";
469     case InlineAsm::Constraint_ZQ:
470       return "ZQ";
471     case InlineAsm::Constraint_ZR:
472       return "ZR";
473     case InlineAsm::Constraint_ZS:
474       return "ZS";
475     case InlineAsm::Constraint_ZT:
476       return "ZT";
477     default:
478       llvm_unreachable("Unknown memory constraint");
479     }
480   }
481 };
482 
483 } // end namespace llvm
484 
485 #endif // LLVM_IR_INLINEASM_H
486