1 //===-- echo.cpp - tool for testing libLLVM and llvm-c API ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the --echo command in llvm-c-test.
12 // This command uses the C API to read a module and output an exact copy of it
13 // as output. It is used to check that the resulting module matches the input
14 // to validate that the C API can read and write modules properly.
16 //===----------------------------------------------------------------------===//
18 #include "llvm-c-test.h"
19 #include "llvm-c/Target.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Support/ErrorHandling.h"
28 // Provide DenseMapInfo for C API opaque types.
30 struct CAPIDenseMap
{};
32 // The default DenseMapInfo require to know about pointer alignement.
33 // Because the C API uses opaques pointer types, their alignement is unknown.
34 // As a result, we need to roll out our own implementation.
36 struct CAPIDenseMap
<T
*> {
37 struct CAPIDenseMapInfo
{
38 static inline T
* getEmptyKey() {
39 uintptr_t Val
= static_cast<uintptr_t>(-1);
40 return reinterpret_cast<T
*>(Val
);
42 static inline T
* getTombstoneKey() {
43 uintptr_t Val
= static_cast<uintptr_t>(-2);
44 return reinterpret_cast<T
*>(Val
);
46 static unsigned getHashValue(const T
*PtrVal
) {
47 return hash_value(PtrVal
);
49 static bool isEqual(const T
*LHS
, const T
*RHS
) { return LHS
== RHS
; }
52 typedef DenseMap
<T
*, T
*, CAPIDenseMapInfo
> Map
;
55 typedef CAPIDenseMap
<LLVMValueRef
>::Map ValueMap
;
56 typedef CAPIDenseMap
<LLVMBasicBlockRef
>::Map BasicBlockMap
;
62 TypeCloner(LLVMModuleRef M
): M(M
), Ctx(LLVMGetModuleContext(M
)) {}
64 LLVMTypeRef
Clone(LLVMValueRef Src
) {
65 return Clone(LLVMTypeOf(Src
));
68 LLVMTypeRef
Clone(LLVMTypeRef Src
) {
69 LLVMTypeKind Kind
= LLVMGetTypeKind(Src
);
71 case LLVMVoidTypeKind
:
72 return LLVMVoidTypeInContext(Ctx
);
73 case LLVMHalfTypeKind
:
74 return LLVMHalfTypeInContext(Ctx
);
75 case LLVMFloatTypeKind
:
76 return LLVMFloatTypeInContext(Ctx
);
77 case LLVMDoubleTypeKind
:
78 return LLVMDoubleTypeInContext(Ctx
);
79 case LLVMX86_FP80TypeKind
:
80 return LLVMX86FP80TypeInContext(Ctx
);
81 case LLVMFP128TypeKind
:
82 return LLVMFP128TypeInContext(Ctx
);
83 case LLVMPPC_FP128TypeKind
:
84 return LLVMPPCFP128TypeInContext(Ctx
);
85 case LLVMLabelTypeKind
:
86 return LLVMLabelTypeInContext(Ctx
);
87 case LLVMIntegerTypeKind
:
88 return LLVMIntTypeInContext(Ctx
, LLVMGetIntTypeWidth(Src
));
89 case LLVMFunctionTypeKind
: {
90 unsigned ParamCount
= LLVMCountParamTypes(Src
);
91 LLVMTypeRef
* Params
= nullptr;
93 Params
= static_cast<LLVMTypeRef
*>(
94 safe_malloc(ParamCount
* sizeof(LLVMTypeRef
)));
95 LLVMGetParamTypes(Src
, Params
);
96 for (unsigned i
= 0; i
< ParamCount
; i
++)
97 Params
[i
] = Clone(Params
[i
]);
100 LLVMTypeRef FunTy
= LLVMFunctionType(Clone(LLVMGetReturnType(Src
)),
102 LLVMIsFunctionVarArg(Src
));
107 case LLVMStructTypeKind
: {
108 LLVMTypeRef S
= nullptr;
109 const char *Name
= LLVMGetStructName(Src
);
111 S
= LLVMGetTypeByName(M
, Name
);
114 S
= LLVMStructCreateNamed(Ctx
, Name
);
115 if (LLVMIsOpaqueStruct(Src
))
119 unsigned EltCount
= LLVMCountStructElementTypes(Src
);
120 SmallVector
<LLVMTypeRef
, 8> Elts
;
121 for (unsigned i
= 0; i
< EltCount
; i
++)
122 Elts
.push_back(Clone(LLVMStructGetTypeAtIndex(Src
, i
)));
124 LLVMStructSetBody(S
, Elts
.data(), EltCount
, LLVMIsPackedStruct(Src
));
126 S
= LLVMStructTypeInContext(Ctx
, Elts
.data(), EltCount
,
127 LLVMIsPackedStruct(Src
));
130 case LLVMArrayTypeKind
:
131 return LLVMArrayType(
132 Clone(LLVMGetElementType(Src
)),
133 LLVMGetArrayLength(Src
)
135 case LLVMPointerTypeKind
:
136 return LLVMPointerType(
137 Clone(LLVMGetElementType(Src
)),
138 LLVMGetPointerAddressSpace(Src
)
140 case LLVMVectorTypeKind
:
141 return LLVMVectorType(
142 Clone(LLVMGetElementType(Src
)),
143 LLVMGetVectorSize(Src
)
145 case LLVMMetadataTypeKind
:
146 return LLVMMetadataTypeInContext(Ctx
);
147 case LLVMX86_MMXTypeKind
:
148 return LLVMX86MMXTypeInContext(Ctx
);
149 case LLVMTokenTypeKind
:
150 return LLVMTokenTypeInContext(Ctx
);
153 fprintf(stderr
, "%d is not a supported typekind\n", Kind
);
158 static ValueMap
clone_params(LLVMValueRef Src
, LLVMValueRef Dst
) {
159 unsigned Count
= LLVMCountParams(Src
);
160 if (Count
!= LLVMCountParams(Dst
))
161 report_fatal_error("Parameter count mismatch");
167 LLVMValueRef SrcFirst
= LLVMGetFirstParam(Src
);
168 LLVMValueRef DstFirst
= LLVMGetFirstParam(Dst
);
169 LLVMValueRef SrcLast
= LLVMGetLastParam(Src
);
170 LLVMValueRef DstLast
= LLVMGetLastParam(Dst
);
172 LLVMValueRef SrcCur
= SrcFirst
;
173 LLVMValueRef DstCur
= DstFirst
;
174 LLVMValueRef SrcNext
= nullptr;
175 LLVMValueRef DstNext
= nullptr;
178 const char *Name
= LLVMGetValueName2(SrcCur
, &NameLen
);
179 LLVMSetValueName2(DstCur
, Name
, NameLen
);
181 VMap
[SrcCur
] = DstCur
;
184 SrcNext
= LLVMGetNextParam(SrcCur
);
185 DstNext
= LLVMGetNextParam(DstCur
);
186 if (SrcNext
== nullptr && DstNext
== nullptr) {
187 if (SrcCur
!= SrcLast
)
188 report_fatal_error("SrcLast param does not match End");
189 if (DstCur
!= DstLast
)
190 report_fatal_error("DstLast param does not match End");
194 if (SrcNext
== nullptr)
195 report_fatal_error("SrcNext was unexpectedly null");
196 if (DstNext
== nullptr)
197 report_fatal_error("DstNext was unexpectedly null");
199 LLVMValueRef SrcPrev
= LLVMGetPreviousParam(SrcNext
);
200 if (SrcPrev
!= SrcCur
)
201 report_fatal_error("SrcNext.Previous param is not Current");
203 LLVMValueRef DstPrev
= LLVMGetPreviousParam(DstNext
);
204 if (DstPrev
!= DstCur
)
205 report_fatal_error("DstNext.Previous param is not Current");
212 report_fatal_error("Parameter count does not match iteration");
217 static void check_value_kind(LLVMValueRef V
, LLVMValueKind K
) {
218 if (LLVMGetValueKind(V
) != K
)
219 report_fatal_error("LLVMGetValueKind returned incorrect type");
222 static LLVMValueRef
clone_constant_impl(LLVMValueRef Cst
, LLVMModuleRef M
);
224 static LLVMValueRef
clone_constant(LLVMValueRef Cst
, LLVMModuleRef M
) {
225 LLVMValueRef Ret
= clone_constant_impl(Cst
, M
);
226 check_value_kind(Ret
, LLVMGetValueKind(Cst
));
230 static LLVMValueRef
clone_constant_impl(LLVMValueRef Cst
, LLVMModuleRef M
) {
231 if (!LLVMIsAConstant(Cst
))
232 report_fatal_error("Expected a constant");
234 // Maybe it is a symbol
235 if (LLVMIsAGlobalValue(Cst
)) {
237 const char *Name
= LLVMGetValueName2(Cst
, &NameLen
);
240 if (LLVMIsAFunction(Cst
)) {
241 check_value_kind(Cst
, LLVMFunctionValueKind
);
242 LLVMValueRef Dst
= LLVMGetNamedFunction(M
, Name
);
245 report_fatal_error("Could not find function");
248 // Try global variable
249 if (LLVMIsAGlobalVariable(Cst
)) {
250 check_value_kind(Cst
, LLVMGlobalVariableValueKind
);
251 LLVMValueRef Dst
= LLVMGetNamedGlobal(M
, Name
);
254 report_fatal_error("Could not find variable");
258 if (LLVMIsAGlobalAlias(Cst
)) {
259 check_value_kind(Cst
, LLVMGlobalAliasValueKind
);
260 LLVMValueRef Dst
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
263 report_fatal_error("Could not find alias");
266 fprintf(stderr
, "Could not find @%s\n", Name
);
270 // Try integer literal
271 if (LLVMIsAConstantInt(Cst
)) {
272 check_value_kind(Cst
, LLVMConstantIntValueKind
);
273 return LLVMConstInt(TypeCloner(M
).Clone(Cst
),
274 LLVMConstIntGetZExtValue(Cst
), false);
277 // Try zeroinitializer
278 if (LLVMIsAConstantAggregateZero(Cst
)) {
279 check_value_kind(Cst
, LLVMConstantAggregateZeroValueKind
);
280 return LLVMConstNull(TypeCloner(M
).Clone(Cst
));
283 // Try constant array
284 if (LLVMIsAConstantArray(Cst
)) {
285 check_value_kind(Cst
, LLVMConstantArrayValueKind
);
286 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
287 unsigned EltCount
= LLVMGetArrayLength(Ty
);
288 SmallVector
<LLVMValueRef
, 8> Elts
;
289 for (unsigned i
= 0; i
< EltCount
; i
++)
290 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
291 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
294 // Try contant data array
295 if (LLVMIsAConstantDataArray(Cst
)) {
296 check_value_kind(Cst
, LLVMConstantDataArrayValueKind
);
297 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
298 unsigned EltCount
= LLVMGetArrayLength(Ty
);
299 SmallVector
<LLVMValueRef
, 8> Elts
;
300 for (unsigned i
= 0; i
< EltCount
; i
++)
301 Elts
.push_back(clone_constant(LLVMGetElementAsConstant(Cst
, i
), M
));
302 return LLVMConstArray(LLVMGetElementType(Ty
), Elts
.data(), EltCount
);
305 // Try constant struct
306 if (LLVMIsAConstantStruct(Cst
)) {
307 check_value_kind(Cst
, LLVMConstantStructValueKind
);
308 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
309 unsigned EltCount
= LLVMCountStructElementTypes(Ty
);
310 SmallVector
<LLVMValueRef
, 8> Elts
;
311 for (unsigned i
= 0; i
< EltCount
; i
++)
312 Elts
.push_back(clone_constant(LLVMGetOperand(Cst
, i
), M
));
313 if (LLVMGetStructName(Ty
))
314 return LLVMConstNamedStruct(Ty
, Elts
.data(), EltCount
);
315 return LLVMConstStructInContext(LLVMGetModuleContext(M
), Elts
.data(),
316 EltCount
, LLVMIsPackedStruct(Ty
));
320 if (LLVMIsUndef(Cst
)) {
321 check_value_kind(Cst
, LLVMUndefValueValueKind
);
322 return LLVMGetUndef(TypeCloner(M
).Clone(Cst
));
326 if (LLVMIsNull(Cst
)) {
327 check_value_kind(Cst
, LLVMConstantTokenNoneValueKind
);
328 LLVMTypeRef Ty
= TypeCloner(M
).Clone(Cst
);
329 return LLVMConstNull(Ty
);
333 if (LLVMIsAConstantFP(Cst
)) {
334 check_value_kind(Cst
, LLVMConstantFPValueKind
);
335 report_fatal_error("ConstantFP is not supported");
338 // This kind of constant is not supported
339 if (!LLVMIsAConstantExpr(Cst
))
340 report_fatal_error("Expected a constant expression");
342 // At this point, it must be a constant expression
343 check_value_kind(Cst
, LLVMConstantExprValueKind
);
345 LLVMOpcode Op
= LLVMGetConstOpcode(Cst
);
348 return LLVMConstBitCast(clone_constant(LLVMGetOperand(Cst
, 0), M
),
349 TypeCloner(M
).Clone(Cst
));
351 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
363 FunCloner(LLVMValueRef Src
, LLVMValueRef Dst
): Fun(Dst
),
364 M(LLVMGetGlobalParent(Fun
)), VMap(clone_params(Src
, Dst
)) {}
366 LLVMTypeRef
CloneType(LLVMTypeRef Src
) {
367 return TypeCloner(M
).Clone(Src
);
370 LLVMTypeRef
CloneType(LLVMValueRef Src
) {
371 return TypeCloner(M
).Clone(Src
);
374 // Try to clone everything in the llvm::Value hierarchy.
375 LLVMValueRef
CloneValue(LLVMValueRef Src
) {
376 // First, the value may be constant.
377 if (LLVMIsAConstant(Src
))
378 return clone_constant(Src
, M
);
380 // Function argument should always be in the map already.
381 auto i
= VMap
.find(Src
);
385 if (!LLVMIsAInstruction(Src
))
386 report_fatal_error("Expected an instruction");
388 auto Ctx
= LLVMGetModuleContext(M
);
389 auto Builder
= LLVMCreateBuilderInContext(Ctx
);
390 auto BB
= DeclareBB(LLVMGetInstructionParent(Src
));
391 LLVMPositionBuilderAtEnd(Builder
, BB
);
392 auto Dst
= CloneInstruction(Src
, Builder
);
393 LLVMDisposeBuilder(Builder
);
397 void CloneAttrs(LLVMValueRef Src
, LLVMValueRef Dst
) {
398 auto Ctx
= LLVMGetModuleContext(M
);
399 int ArgCount
= LLVMGetNumArgOperands(Src
);
400 for (int i
= LLVMAttributeReturnIndex
; i
<= ArgCount
; i
++) {
401 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
402 if (auto SrcA
= LLVMGetCallSiteEnumAttribute(Src
, i
, k
)) {
403 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
404 auto A
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
405 LLVMAddCallSiteAttribute(Dst
, i
, A
);
411 LLVMValueRef
CloneInstruction(LLVMValueRef Src
, LLVMBuilderRef Builder
) {
412 check_value_kind(Src
, LLVMInstructionValueKind
);
413 if (!LLVMIsAInstruction(Src
))
414 report_fatal_error("Expected an instruction");
417 const char *Name
= LLVMGetValueName2(Src
, &NameLen
);
419 // Check if this is something we already computed.
421 auto i
= VMap
.find(Src
);
422 if (i
!= VMap
.end()) {
423 // If we have a hit, it means we already generated the instruction
424 // as a dependancy to somethign else. We need to make sure
425 // it is ordered properly.
427 LLVMInstructionRemoveFromParent(I
);
428 LLVMInsertIntoBuilderWithName(Builder
, I
, Name
);
433 // We tried everything, it must be an instruction
434 // that hasn't been generated already.
435 LLVMValueRef Dst
= nullptr;
437 LLVMOpcode Op
= LLVMGetInstructionOpcode(Src
);
440 int OpCount
= LLVMGetNumOperands(Src
);
442 Dst
= LLVMBuildRetVoid(Builder
);
444 Dst
= LLVMBuildRet(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
448 if (!LLVMIsConditional(Src
)) {
449 LLVMValueRef SrcOp
= LLVMGetOperand(Src
, 0);
450 LLVMBasicBlockRef SrcBB
= LLVMValueAsBasicBlock(SrcOp
);
451 Dst
= LLVMBuildBr(Builder
, DeclareBB(SrcBB
));
455 LLVMValueRef Cond
= LLVMGetCondition(Src
);
456 LLVMValueRef Else
= LLVMGetOperand(Src
, 1);
457 LLVMBasicBlockRef ElseBB
= DeclareBB(LLVMValueAsBasicBlock(Else
));
458 LLVMValueRef Then
= LLVMGetOperand(Src
, 2);
459 LLVMBasicBlockRef ThenBB
= DeclareBB(LLVMValueAsBasicBlock(Then
));
460 Dst
= LLVMBuildCondBr(Builder
, CloneValue(Cond
), ThenBB
, ElseBB
);
467 SmallVector
<LLVMValueRef
, 8> Args
;
468 int ArgCount
= LLVMGetNumArgOperands(Src
);
469 for (int i
= 0; i
< ArgCount
; i
++)
470 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
471 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
472 LLVMBasicBlockRef Then
= DeclareBB(LLVMGetNormalDest(Src
));
473 LLVMBasicBlockRef Unwind
= DeclareBB(LLVMGetUnwindDest(Src
));
474 Dst
= LLVMBuildInvoke(Builder
, Fn
, Args
.data(), ArgCount
,
476 CloneAttrs(Src
, Dst
);
479 case LLVMUnreachable
:
480 Dst
= LLVMBuildUnreachable(Builder
);
483 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
484 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
485 Dst
= LLVMBuildAdd(Builder
, LHS
, RHS
, Name
);
489 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
490 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
491 Dst
= LLVMBuildSub(Builder
, LHS
, RHS
, Name
);
495 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
496 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
497 Dst
= LLVMBuildMul(Builder
, LHS
, RHS
, Name
);
501 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
502 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
503 Dst
= LLVMBuildUDiv(Builder
, LHS
, RHS
, Name
);
507 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
508 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
509 Dst
= LLVMBuildSDiv(Builder
, LHS
, RHS
, Name
);
513 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
514 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
515 Dst
= LLVMBuildURem(Builder
, LHS
, RHS
, Name
);
519 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
520 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
521 Dst
= LLVMBuildSRem(Builder
, LHS
, RHS
, Name
);
525 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
526 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
527 Dst
= LLVMBuildShl(Builder
, LHS
, RHS
, Name
);
531 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
532 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
533 Dst
= LLVMBuildLShr(Builder
, LHS
, RHS
, Name
);
537 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
538 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
539 Dst
= LLVMBuildAShr(Builder
, LHS
, RHS
, Name
);
543 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
544 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
545 Dst
= LLVMBuildAnd(Builder
, LHS
, RHS
, Name
);
549 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
550 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
551 Dst
= LLVMBuildOr(Builder
, LHS
, RHS
, Name
);
555 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
556 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
557 Dst
= LLVMBuildXor(Builder
, LHS
, RHS
, Name
);
561 LLVMTypeRef Ty
= CloneType(LLVMGetAllocatedType(Src
));
562 Dst
= LLVMBuildAlloca(Builder
, Ty
, Name
);
566 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
567 Dst
= LLVMBuildLoad(Builder
, Ptr
, Name
);
568 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
572 LLVMValueRef Val
= CloneValue(LLVMGetOperand(Src
, 0));
573 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 1));
574 Dst
= LLVMBuildStore(Builder
, Val
, Ptr
);
575 LLVMSetAlignment(Dst
, LLVMGetAlignment(Src
));
578 case LLVMGetElementPtr
: {
579 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
580 SmallVector
<LLVMValueRef
, 8> Idx
;
581 int NumIdx
= LLVMGetNumIndices(Src
);
582 for (int i
= 1; i
<= NumIdx
; i
++)
583 Idx
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
584 if (LLVMIsInBounds(Src
))
585 Dst
= LLVMBuildInBoundsGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
587 Dst
= LLVMBuildGEP(Builder
, Ptr
, Idx
.data(), NumIdx
, Name
);
590 case LLVMAtomicCmpXchg
: {
591 LLVMValueRef Ptr
= CloneValue(LLVMGetOperand(Src
, 0));
592 LLVMValueRef Cmp
= CloneValue(LLVMGetOperand(Src
, 1));
593 LLVMValueRef New
= CloneValue(LLVMGetOperand(Src
, 2));
594 LLVMAtomicOrdering Succ
= LLVMGetCmpXchgSuccessOrdering(Src
);
595 LLVMAtomicOrdering Fail
= LLVMGetCmpXchgFailureOrdering(Src
);
596 LLVMBool SingleThread
= LLVMIsAtomicSingleThread(Src
);
598 Dst
= LLVMBuildAtomicCmpXchg(Builder
, Ptr
, Cmp
, New
, Succ
, Fail
,
602 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 0));
603 Dst
= LLVMBuildBitCast(Builder
, V
, CloneType(Src
), Name
);
607 LLVMIntPredicate Pred
= LLVMGetICmpPredicate(Src
);
608 LLVMValueRef LHS
= CloneValue(LLVMGetOperand(Src
, 0));
609 LLVMValueRef RHS
= CloneValue(LLVMGetOperand(Src
, 1));
610 Dst
= LLVMBuildICmp(Builder
, Pred
, LHS
, RHS
, Name
);
614 // We need to aggressively set things here because of loops.
615 VMap
[Src
] = Dst
= LLVMBuildPhi(Builder
, CloneType(Src
), Name
);
617 SmallVector
<LLVMValueRef
, 8> Values
;
618 SmallVector
<LLVMBasicBlockRef
, 8> Blocks
;
620 unsigned IncomingCount
= LLVMCountIncoming(Src
);
621 for (unsigned i
= 0; i
< IncomingCount
; ++i
) {
622 Blocks
.push_back(DeclareBB(LLVMGetIncomingBlock(Src
, i
)));
623 Values
.push_back(CloneValue(LLVMGetIncomingValue(Src
, i
)));
626 LLVMAddIncoming(Dst
, Values
.data(), Blocks
.data(), IncomingCount
);
630 SmallVector
<LLVMValueRef
, 8> Args
;
631 int ArgCount
= LLVMGetNumArgOperands(Src
);
632 for (int i
= 0; i
< ArgCount
; i
++)
633 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
634 LLVMValueRef Fn
= CloneValue(LLVMGetCalledValue(Src
));
635 Dst
= LLVMBuildCall(Builder
, Fn
, Args
.data(), ArgCount
, Name
);
636 LLVMSetTailCall(Dst
, LLVMIsTailCall(Src
));
637 CloneAttrs(Src
, Dst
);
641 Dst
= LLVMBuildResume(Builder
, CloneValue(LLVMGetOperand(Src
, 0)));
644 case LLVMLandingPad
: {
645 // The landing pad API is a bit screwed up for historical reasons.
646 Dst
= LLVMBuildLandingPad(Builder
, CloneType(Src
), nullptr, 0, Name
);
647 unsigned NumClauses
= LLVMGetNumClauses(Src
);
648 for (unsigned i
= 0; i
< NumClauses
; ++i
)
649 LLVMAddClause(Dst
, CloneValue(LLVMGetClause(Src
, i
)));
650 LLVMSetCleanup(Dst
, LLVMIsCleanup(Src
));
653 case LLVMCleanupRet
: {
654 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
655 LLVMBasicBlockRef Unwind
= nullptr;
656 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
))
657 Unwind
= DeclareBB(UDest
);
658 Dst
= LLVMBuildCleanupRet(Builder
, CatchPad
, Unwind
);
662 LLVMValueRef CatchPad
= CloneValue(LLVMGetOperand(Src
, 0));
663 LLVMBasicBlockRef SuccBB
= DeclareBB(LLVMGetSuccessor(Src
, 0));
664 Dst
= LLVMBuildCatchRet(Builder
, CatchPad
, SuccBB
);
668 LLVMValueRef ParentPad
= CloneValue(LLVMGetParentCatchSwitch(Src
));
669 SmallVector
<LLVMValueRef
, 8> Args
;
670 int ArgCount
= LLVMGetNumArgOperands(Src
);
671 for (int i
= 0; i
< ArgCount
; i
++)
672 Args
.push_back(CloneValue(LLVMGetOperand(Src
, i
)));
673 Dst
= LLVMBuildCatchPad(Builder
, ParentPad
,
674 Args
.data(), ArgCount
, Name
);
677 case LLVMCleanupPad
: {
678 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
679 SmallVector
<LLVMValueRef
, 8> Args
;
680 int ArgCount
= LLVMGetNumArgOperands(Src
);
681 for (int i
= 0; i
< ArgCount
; i
++)
682 Args
.push_back(CloneValue(LLVMGetArgOperand(Src
, i
)));
683 Dst
= LLVMBuildCleanupPad(Builder
, ParentPad
,
684 Args
.data(), ArgCount
, Name
);
687 case LLVMCatchSwitch
: {
688 LLVMValueRef ParentPad
= CloneValue(LLVMGetOperand(Src
, 0));
689 LLVMBasicBlockRef UnwindBB
= nullptr;
690 if (LLVMBasicBlockRef UDest
= LLVMGetUnwindDest(Src
)) {
691 UnwindBB
= DeclareBB(UDest
);
693 unsigned NumHandlers
= LLVMGetNumHandlers(Src
);
694 Dst
= LLVMBuildCatchSwitch(Builder
, ParentPad
, UnwindBB
, NumHandlers
, Name
);
695 if (NumHandlers
> 0) {
696 LLVMBasicBlockRef
*Handlers
= static_cast<LLVMBasicBlockRef
*>(
697 safe_malloc(NumHandlers
* sizeof(LLVMBasicBlockRef
)));
698 LLVMGetHandlers(Src
, Handlers
);
699 for (unsigned i
= 0; i
< NumHandlers
; i
++)
700 LLVMAddHandler(Dst
, DeclareBB(Handlers
[i
]));
705 case LLVMExtractValue
: {
706 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
707 if (LLVMGetNumIndices(Src
) != 1)
708 report_fatal_error("Expected only one indice");
709 auto I
= LLVMGetIndices(Src
)[0];
710 Dst
= LLVMBuildExtractValue(Builder
, Agg
, I
, Name
);
713 case LLVMInsertValue
: {
714 LLVMValueRef Agg
= CloneValue(LLVMGetOperand(Src
, 0));
715 LLVMValueRef V
= CloneValue(LLVMGetOperand(Src
, 1));
716 if (LLVMGetNumIndices(Src
) != 1)
717 report_fatal_error("Expected only one indice");
718 auto I
= LLVMGetIndices(Src
)[0];
719 Dst
= LLVMBuildInsertValue(Builder
, Agg
, V
, I
, Name
);
726 if (Dst
== nullptr) {
727 fprintf(stderr
, "%d is not a supported opcode\n", Op
);
731 check_value_kind(Dst
, LLVMInstructionValueKind
);
732 return VMap
[Src
] = Dst
;
735 LLVMBasicBlockRef
DeclareBB(LLVMBasicBlockRef Src
) {
736 // Check if this is something we already computed.
738 auto i
= BBMap
.find(Src
);
739 if (i
!= BBMap
.end()) {
744 LLVMValueRef V
= LLVMBasicBlockAsValue(Src
);
745 if (!LLVMValueIsBasicBlock(V
) || LLVMValueAsBasicBlock(V
) != Src
)
746 report_fatal_error("Basic block is not a basic block");
748 const char *Name
= LLVMGetBasicBlockName(Src
);
750 const char *VName
= LLVMGetValueName2(V
, &NameLen
);
752 report_fatal_error("Basic block name mismatch");
754 LLVMBasicBlockRef BB
= LLVMAppendBasicBlock(Fun
, Name
);
755 return BBMap
[Src
] = BB
;
758 LLVMBasicBlockRef
CloneBB(LLVMBasicBlockRef Src
) {
759 LLVMBasicBlockRef BB
= DeclareBB(Src
);
761 // Make sure ordering is correct.
762 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Src
);
764 LLVMMoveBasicBlockAfter(BB
, DeclareBB(Prev
));
766 LLVMValueRef First
= LLVMGetFirstInstruction(Src
);
767 LLVMValueRef Last
= LLVMGetLastInstruction(Src
);
769 if (First
== nullptr) {
771 report_fatal_error("Has no first instruction, but last one");
775 auto Ctx
= LLVMGetModuleContext(M
);
776 LLVMBuilderRef Builder
= LLVMCreateBuilderInContext(Ctx
);
777 LLVMPositionBuilderAtEnd(Builder
, BB
);
779 LLVMValueRef Cur
= First
;
780 LLVMValueRef Next
= nullptr;
782 CloneInstruction(Cur
, Builder
);
783 Next
= LLVMGetNextInstruction(Cur
);
784 if (Next
== nullptr) {
786 report_fatal_error("Final instruction does not match Last");
790 LLVMValueRef Prev
= LLVMGetPreviousInstruction(Next
);
792 report_fatal_error("Next.Previous instruction is not Current");
797 LLVMDisposeBuilder(Builder
);
801 void CloneBBs(LLVMValueRef Src
) {
802 unsigned Count
= LLVMCountBasicBlocks(Src
);
806 LLVMBasicBlockRef First
= LLVMGetFirstBasicBlock(Src
);
807 LLVMBasicBlockRef Last
= LLVMGetLastBasicBlock(Src
);
809 LLVMBasicBlockRef Cur
= First
;
810 LLVMBasicBlockRef Next
= nullptr;
814 Next
= LLVMGetNextBasicBlock(Cur
);
815 if (Next
== nullptr) {
817 report_fatal_error("Final basic block does not match Last");
821 LLVMBasicBlockRef Prev
= LLVMGetPreviousBasicBlock(Next
);
823 report_fatal_error("Next.Previous basic bloc is not Current");
829 report_fatal_error("Basic block count does not match iterration");
833 static void declare_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
834 auto Ctx
= LLVMGetModuleContext(M
);
836 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
837 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
839 LLVMValueRef Cur
= Begin
;
840 LLVMValueRef Next
= nullptr;
843 report_fatal_error("Range has an end but no beginning");
849 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
850 if (LLVMGetNamedGlobal(M
, Name
))
851 report_fatal_error("GlobalVariable already cloned");
852 LLVMAddGlobal(M
, LLVMGetElementType(TypeCloner(M
).Clone(Cur
)), Name
);
854 Next
= LLVMGetNextGlobal(Cur
);
855 if (Next
== nullptr) {
857 report_fatal_error("");
861 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
863 report_fatal_error("Next.Previous global is not Current");
869 Begin
= LLVMGetFirstFunction(Src
);
870 End
= LLVMGetLastFunction(Src
);
873 report_fatal_error("Range has an end but no beginning");
881 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
882 if (LLVMGetNamedFunction(M
, Name
))
883 report_fatal_error("Function already cloned");
884 auto Ty
= LLVMGetElementType(TypeCloner(M
).Clone(Cur
));
885 auto F
= LLVMAddFunction(M
, Name
, Ty
);
888 for (int i
= LLVMAttributeFunctionIndex
, c
= LLVMCountParams(F
);
890 for (unsigned k
= 0, e
= LLVMGetLastEnumAttributeKind(); k
< e
; ++k
) {
891 if (auto SrcA
= LLVMGetEnumAttributeAtIndex(Cur
, i
, k
)) {
892 auto Val
= LLVMGetEnumAttributeValue(SrcA
);
893 auto DstA
= LLVMCreateEnumAttribute(Ctx
, k
, Val
);
894 LLVMAddAttributeAtIndex(F
, i
, DstA
);
899 Next
= LLVMGetNextFunction(Cur
);
900 if (Next
== nullptr) {
902 report_fatal_error("Last function does not match End");
906 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
908 report_fatal_error("Next.Previous function is not Current");
914 Begin
= LLVMGetFirstGlobalAlias(Src
);
915 End
= LLVMGetLastGlobalAlias(Src
);
918 report_fatal_error("Range has an end but no beginning");
926 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
927 if (LLVMGetNamedGlobalAlias(M
, Name
, NameLen
))
928 report_fatal_error("Global alias already cloned");
929 LLVMTypeRef CurType
= TypeCloner(M
).Clone(Cur
);
930 // FIXME: Allow NULL aliasee.
931 LLVMAddAlias(M
, CurType
, LLVMGetUndef(CurType
), Name
);
933 Next
= LLVMGetNextGlobalAlias(Cur
);
934 if (Next
== nullptr) {
936 report_fatal_error("");
940 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
942 report_fatal_error("Next.Previous global is not Current");
948 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
949 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
951 if (EndMD
!= nullptr)
952 report_fatal_error("Range has an end but no beginning");
956 LLVMNamedMDNodeRef CurMD
= BeginMD
;
957 LLVMNamedMDNodeRef NextMD
= nullptr;
960 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
961 if (LLVMGetNamedMetadata(M
, Name
, NameLen
))
962 report_fatal_error("Named Metadata Node already cloned");
963 LLVMGetOrInsertNamedMetadata(M
, Name
, NameLen
);
965 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
966 if (NextMD
== nullptr) {
968 report_fatal_error("");
972 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
974 report_fatal_error("Next.Previous global is not Current");
980 static void clone_symbols(LLVMModuleRef Src
, LLVMModuleRef M
) {
981 LLVMValueRef Begin
= LLVMGetFirstGlobal(Src
);
982 LLVMValueRef End
= LLVMGetLastGlobal(Src
);
984 LLVMValueRef Cur
= Begin
;
985 LLVMValueRef Next
= nullptr;
988 report_fatal_error("Range has an end but no beginning");
994 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
995 LLVMValueRef G
= LLVMGetNamedGlobal(M
, Name
);
997 report_fatal_error("GlobalVariable must have been declared already");
999 if (auto I
= LLVMGetInitializer(Cur
))
1000 LLVMSetInitializer(G
, clone_constant(I
, M
));
1002 LLVMSetGlobalConstant(G
, LLVMIsGlobalConstant(Cur
));
1003 LLVMSetThreadLocal(G
, LLVMIsThreadLocal(Cur
));
1004 LLVMSetExternallyInitialized(G
, LLVMIsExternallyInitialized(Cur
));
1005 LLVMSetLinkage(G
, LLVMGetLinkage(Cur
));
1006 LLVMSetSection(G
, LLVMGetSection(Cur
));
1007 LLVMSetVisibility(G
, LLVMGetVisibility(Cur
));
1008 LLVMSetUnnamedAddress(G
, LLVMGetUnnamedAddress(Cur
));
1009 LLVMSetAlignment(G
, LLVMGetAlignment(Cur
));
1011 Next
= LLVMGetNextGlobal(Cur
);
1012 if (Next
== nullptr) {
1014 report_fatal_error("");
1018 LLVMValueRef Prev
= LLVMGetPreviousGlobal(Next
);
1020 report_fatal_error("Next.Previous global is not Current");
1026 Begin
= LLVMGetFirstFunction(Src
);
1027 End
= LLVMGetLastFunction(Src
);
1030 report_fatal_error("Range has an end but no beginning");
1038 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1039 LLVMValueRef Fun
= LLVMGetNamedFunction(M
, Name
);
1041 report_fatal_error("Function must have been declared already");
1043 if (LLVMHasPersonalityFn(Cur
)) {
1045 const char *FName
= LLVMGetValueName2(LLVMGetPersonalityFn(Cur
),
1047 LLVMValueRef P
= LLVMGetNamedFunction(M
, FName
);
1049 report_fatal_error("Could not find personality function");
1050 LLVMSetPersonalityFn(Fun
, P
);
1053 FunCloner
FC(Cur
, Fun
);
1056 Next
= LLVMGetNextFunction(Cur
);
1057 if (Next
== nullptr) {
1059 report_fatal_error("Last function does not match End");
1063 LLVMValueRef Prev
= LLVMGetPreviousFunction(Next
);
1065 report_fatal_error("Next.Previous function is not Current");
1071 Begin
= LLVMGetFirstGlobalAlias(Src
);
1072 End
= LLVMGetLastGlobalAlias(Src
);
1075 report_fatal_error("Range has an end but no beginning");
1083 const char *Name
= LLVMGetValueName2(Cur
, &NameLen
);
1084 LLVMValueRef Alias
= LLVMGetNamedGlobalAlias(M
, Name
, NameLen
);
1086 report_fatal_error("Global alias must have been declared already");
1088 if (LLVMValueRef Aliasee
= LLVMAliasGetAliasee(Cur
)) {
1089 LLVMAliasSetAliasee(Alias
, clone_constant(Aliasee
, M
));
1092 LLVMSetLinkage(Alias
, LLVMGetLinkage(Cur
));
1093 LLVMSetUnnamedAddress(Alias
, LLVMGetUnnamedAddress(Cur
));
1095 Next
= LLVMGetNextGlobalAlias(Cur
);
1096 if (Next
== nullptr) {
1098 report_fatal_error("Last global alias does not match End");
1102 LLVMValueRef Prev
= LLVMGetPreviousGlobalAlias(Next
);
1104 report_fatal_error("Next.Previous global alias is not Current");
1110 LLVMNamedMDNodeRef BeginMD
= LLVMGetFirstNamedMetadata(Src
);
1111 LLVMNamedMDNodeRef EndMD
= LLVMGetLastNamedMetadata(Src
);
1113 if (EndMD
!= nullptr)
1114 report_fatal_error("Range has an end but no beginning");
1118 LLVMNamedMDNodeRef CurMD
= BeginMD
;
1119 LLVMNamedMDNodeRef NextMD
= nullptr;
1122 const char *Name
= LLVMGetNamedMetadataName(CurMD
, &NameLen
);
1123 LLVMNamedMDNodeRef NamedMD
= LLVMGetNamedMetadata(M
, Name
, NameLen
);
1125 report_fatal_error("Named MD Node must have been declared already");
1127 unsigned OperandCount
= LLVMGetNamedMetadataNumOperands(Src
, Name
);
1128 LLVMValueRef
*OperandBuf
= static_cast<LLVMValueRef
*>(
1129 safe_malloc(OperandCount
* sizeof(LLVMValueRef
)));
1130 LLVMGetNamedMetadataOperands(Src
, Name
, OperandBuf
);
1131 for (unsigned i
= 0, e
= OperandCount
; i
!= e
; ++i
) {
1132 LLVMAddNamedMetadataOperand(M
, Name
, OperandBuf
[i
]);
1136 NextMD
= LLVMGetNextNamedMetadata(CurMD
);
1137 if (NextMD
== nullptr) {
1139 report_fatal_error("Last Named MD Node does not match End");
1143 LLVMNamedMDNodeRef PrevMD
= LLVMGetPreviousNamedMetadata(NextMD
);
1144 if (PrevMD
!= CurMD
)
1145 report_fatal_error("Next.Previous Named MD Node is not Current");
1151 int llvm_echo(void) {
1152 LLVMEnablePrettyStackTrace();
1154 LLVMModuleRef Src
= llvm_load_module(false, true);
1155 size_t SourceFileLen
;
1156 const char *SourceFileName
= LLVMGetSourceFileName(Src
, &SourceFileLen
);
1157 size_t ModuleIdentLen
;
1158 const char *ModuleName
= LLVMGetModuleIdentifier(Src
, &ModuleIdentLen
);
1159 LLVMContextRef Ctx
= LLVMContextCreate();
1160 LLVMModuleRef M
= LLVMModuleCreateWithNameInContext(ModuleName
, Ctx
);
1162 LLVMSetSourceFileName(M
, SourceFileName
, SourceFileLen
);
1163 LLVMSetModuleIdentifier(M
, ModuleName
, ModuleIdentLen
);
1165 LLVMSetTarget(M
, LLVMGetTarget(Src
));
1166 LLVMSetModuleDataLayout(M
, LLVMGetModuleDataLayout(Src
));
1167 if (strcmp(LLVMGetDataLayoutStr(M
), LLVMGetDataLayoutStr(Src
)))
1168 report_fatal_error("Inconsistent DataLayout string representation");
1170 size_t ModuleInlineAsmLen
;
1171 const char *ModuleAsm
= LLVMGetModuleInlineAsm(Src
, &ModuleInlineAsmLen
);
1172 LLVMSetModuleInlineAsm2(M
, ModuleAsm
, ModuleInlineAsmLen
);
1174 declare_symbols(Src
, M
);
1175 clone_symbols(Src
, M
);
1176 char *Str
= LLVMPrintModuleToString(M
);
1179 LLVMDisposeMessage(Str
);
1180 LLVMDisposeModule(Src
);
1181 LLVMDisposeModule(M
);
1182 LLVMContextDispose(Ctx
);